Expand description
Dynamic shell completion engine for CLI tools.
Provides a generic, tree-based completion system that completes one level
at a time (no eager subcommand chaining). The caller defines the command
tree via CommandTree, and this crate handles:
- Walking the tree to find candidates for a given input
- Filtering out options already present on the command line
- Handling bare
key=valueparams alongside--flagoptions - Dynamic option discovery from command-line context (e.g., reading a workload file to discover its declared parameters)
- Generating bash completion scripts
- Handling the
_<APP>_COMPLETE=bashenv var callbacks
§Usage
use veks_completion::{CommandTree, Node, complete, print_bash_script, handle_complete_env};
let tree = CommandTree::new("myapp")
.command("run", Node::leaf(&["--dry-run", "--threads"]))
.command("check", Node::leaf(&["--all", "--quiet"]))
.group("pipeline", Node::group(vec![
("compute", Node::group(vec![
("knn", Node::leaf(&["--base", "--query", "--metric"])),
])),
]));
// In main():
if handle_complete_env("myapp", &tree) {
std::process::exit(0);
}Re-exports§
pub use cli::render_help;pub use cli::CommandSpec;pub use cli::OptionSpec;pub use cli::ParsedArgs;pub use cli::PositionalSpec;pub use cli::VeksCli;pub use options::CommandOption;pub use options::OptionConflict;pub use options::OptionDef;pub use options::OptionRegistry;pub use options::ParseMismatch;
Modules§
- cli
- The veks-completion CLI framework: argument parsing, help, and a command definition model — the in-tree replacement for clap.
- options
- Shared, per-command option definitions with a project-wide consistency guarantee.
- providers
- Built-in
SubtreeProviders that downstream embedders can attach to aNodeto enable common context-sensitive completion scenarios without implementing a grammar from scratch.
Structs§
- Bracket
State - Bracket / quote depth at the cursor, computed by
PartialParse::bracket_state. Lets a grammar-aware provider answer “am I inside a{...},(...),[...], or quoted string?” without re-implementing the scanner. - Command
Tree - The top-level command tree for an application.
- Directive
- A richer flag descriptor that bundles the CLI form, optional
YAML mirror, value semantics, and repeatability into one
declaration. Adapters can expand a
&[Directive]into per-flag completion + parse rules without the caller writing a parallel translation layer. - Extras
- Free-form payload slot on a Node (TODO item 8). Wraps an
Arc<dyn Any + Send + Sync>so embedders can attach handler types, parser state, or anything else without forcing veks-completion to grow generic parameters or hard dependencies. - Node
- Carries two metadata fields used by stratified (multi-tap) completion:
- Parsed
Command - Result of
parse_argv— a structured view of an argv vector against aCommandTree. Embedders use this to dispatch handlers without writing a parallel walker. - Partial
Parse - Structured snapshot of the partial command-line state at the
cursor position. Passed to subtree providers so they can offer
context-aware completions without re-tokenising
COMP_LINE. - Strict
Node - Type-state wrapper around
Nodethat tracks at the type level whether the node has been given a category and an explicit tap-tier level. - TapState
- Persistable tap state — the bytes a driver would write between
tap events. Two fields: the wall-clock ms at which the tap
happened, and the count to persist (which is the layer just
shown, or 0 if we just closed the cycle by hitting
max_level).
Enums§
- Closed
Values - A closed set of valid values for a flag. Both static (
&'static [&'static str]) and runtime-owned (Vec<String>) variants are supported via the same query API. - Metadata
Error - Errors produced by
CommandTree::validate. - Parse
Error - Errors returned by
parse_argv. - Shell
- Supported shells for completion-script generation.
- Stability
- A node in the command tree.
Constants§
- DEFAULT_
LEVEL - Default visibility tier when a node doesn’t explicitly opt into a higher tier. Tier 1 means “show on the very first tab tap” — preserves the pre-stratification behavior for existing apps that haven’t categorized their commands.
- DIAGNOSTIC_
FLAGS - Check for completion env vars and handle them.
- SUBTREE_
PROVIDER_ MAX_ TAPS - Cap on rapid-tap advancement when the resolved completion path
includes a
SubtreeProvider. The provider owns its candidate output and may layer it by tap (e.g. tap 1 = primary set, tap 2 = primary + secondary), so the engine can’t infer a meaningful max from tree shape alone. This constant defines how many tap tiers the engine will surface to a provider before the cadence rule resets back to tap 1. - TAP_
ADVANCE_ MS - Window inside which a same-key tap counts as a rapid follow-up and advances to the next layer. Outside this window, the next tap starts fresh at layer 1. Exposed so embedders can mention or match the same value in their own UX.
Traits§
- Category
Tag - Discovery-category abstraction.
- Level
Tag - Discovery-tier abstraction symmetric with
CategoryTag.
Functions§
- apply_
directives - Apply a slice of
Directives to aNodein one call. Each directive becomes: - closed_
set - Build a
ValueProviderover a fixed set of candidate values, filtered by the typed prefix. This is the completion side of a closed-set option — e.g. the derive emits it for#[arg(value_parser = ["text", "csv", "json"])]so the same single declaration that drives parsing also feeds tab-completion. - complete
- Compute completion candidates for the given input words.
- complete_
at_ level_ only - Rotating-tier completion. Returns root-level candidates whose
Node::level() == only_level(NOT the cumulative<=set), so successive tab taps cycle through tiers one at a time and wrap around after the highest. Once the user starts typing a specific name, behaves identically tocomplete— the level filter applies only at the root with an empty partial. - complete_
at_ tap - Stratified completion: returns root-level candidates with
Node::level() <= tap_count, so the Nth tab tap reveals progressively more commands. Inside a subcommand or with a non-empty partial, behaves identically tocomplete— the level filter applies only when the user is at the root prompt with no prefix typed. - complete_
at_ tap_ with_ raw - Same as
complete_at_tapbut additionally accepts the rawCOMP_LINEand the cursor’s byte offset. Subtree providers receive these inPartialParse::raw_line/PartialParse::cursor_offset, enabling grammar-aware completion (e.g. for embedded query DSLs like MetricsQL or PromQL where bracket / quote / operator state at the cursor matters). - complete_
expanded - Expanded completion: show all
group commandpairs. - complete_
rotating - Convenience wrapper over
complete_at_level_onlythat maps the raw tap counter to the rotating level. Cycle length is computed relative to whichever group node the user has descended into — a subgroup with only level-1 children has a cycle length of 1 (every tap shows the same set), while a subgroup with Primary+Secondary+Advanced children has a cycle length of 3. A tap beyond the cycle wraps back to level 1. - complete_
rotating_ with_ raw - Same as
complete_rotatingbut additionally threads the rawCOMP_LINEand cursor offset through to subtree providers viaPartialParse::raw_line/PartialParse::cursor_offset. Used byhandle_complete_envso grammar-aware providers can inspect raw text + cursor position. - completions_
registered_ marker - The environment variable the completion-registration script exports to mark
that completions are wired up in the current shell — e.g.
_VECTORDATA_COMPLETIONS_REGISTERED. The binary checks it (seehint_completions_unregistered) to decide whether to nudge the user. - detect_
shell - Detect the user’s interactive shell.
- fn_
provider - Helper to wrap a
fn-pointer provider into the closure-typedValueProvider. Most existing global providers use plainfnpointers and call this when registering. - handle_
complete_ env - handle_
diagnostic_ args - Triple-dash diagnostic dispatcher. Inspect
std::env::argsfor a recognised---*flag (seeDIAGNOSTIC_FLAGS) and, if found, run the corresponding diagnostic and returntrue. The caller shouldprocess::exit(0)(or just return) when this returns true, exactly likehandle_complete_env. - hint_
completions_ unregistered - Print a one-line nudge to stderr when tab-completion for
app_nameis not yet enabled in this shell, telling the user how to turn it on permanently. Call once per normal (non-completion) invocation. - next_
tap_ state - Pure cadence rule. Given the previous persisted state (and the input key it was recorded against), the current time, the current input key, and the max layer count for the current group, returns:
- parse_
argv - Parse
argv(excluding the program name) against the suppliedCommandTree. Walks subcommands, collects flags, separates positionals. - parse_
argv_ lenient - Lenient variant of
parse_argv— unknown flags are treated as positionals rather than rejected. Useful for “pass-through” CLIs that wrap external commands. - print_
bash_ script - Generate a bash completion script that calls back into the app.
- print_
completions - Print a direct completion script for
<app> completions --shell <shell>. This is what the indirect wrapper sources at shell startup; callers can invoke it directly when they want the raw script in stdout. - print_
indirect_ wrapper - Print a completions snippet for
<app> completions(no--shell) — the convenience entry point users typically call once at shell startup. Auto-detects the user’s shell and emits a comment header plus an indirect-source <(...)line that pulls the actual script from<app> completions --shell <shell>. - print_
partial_ parse_ for_ diagnostics - Pretty-print the engine’s view of a
PartialParsefor the---trace-partial-parseand downstream provider diagnostic flags. Public so provider-specific diagnostic dispatchers (e.g.crate::providers::metricsql_diagnostic_args) can reuse the same output format. - render_
usage - Render a
--help-style usage block for a node at the given path (TODO item 6). The same model that drives tab completion drives help, so the two surfaces can’t drift. - shell_
ready_ candidates - Convert semantic candidates into the exact bytes handed to bash.
- trace_
completion_ candidates - Pure core of the
---trace-completiondiagnostic: run the completion engine foruser_line(the command line as typed AFTER the binary name, e.g."datasets li") with the cursor at byte offsetuser_pointwithin it (default: end of line), and return exactly the lines the diagnostic prints.
Type Aliases§
- Dynamic
Options Provider - A function that provides additional option candidates based on context.
- Subtree
Provider - Type alias for group-level context-aware completion providers
(TODO item 7). Receives a structured
PartialParseof the command line state and returns candidates to merge into the completer’s output. - Value
Provider - A function that provides dynamic completion values for a specific option.