// ZSH-CARGO-COMPLETION — ENGINEERING REPORT

#compdef cargo · live cargo search-backed remote crate completion · _retrieve_cache / _store_cache 2-tier memoization · full OMZ cargo subcommand surface

>_EXECUTIVE SUMMARY

zsh-cargo-completion ships every cargo subcommand + flag completion that Oh My Zsh's cargo plugin carries, plus a live cargo search-backed completer for the remote-crate-name positional argument of cargo add and cargo install. Type cargo add ran<TAB> and the completer fires cargo search --color=never --limit 1000 -q ran, parses the response, caches it via zsh's built-in _retrieve_cache / _store_cache memoization layer (so the next TAB against the same prefix is local), and feeds the resulting crate:description pairs to _describe. Total surface: 450 lines in src/_cargo, plus a 23-line plugin entry that adds ${0:h}/src to fpath and exposes 17 cargo aliases473 zsh lines total. The completion engine is one top-level dispatcher (_cargo), one live-index completer (__cargo_remote_packages), and 8 helper completion functions, with a case ${words[1]} statement that fans out into 32 per-subcommand _arguments arms. Pinned by 172 @test blocks across 6 zunit files, plus 21 portable tests/*.sh gates.

473
Zsh Lines
450
_cargo Lines
172
@test Blocks (zunit)
6
Test Files
32
Subcommand Arms
17
Cargo Aliases
8
Helper Fns
31
_arguments Blocks

~ARCHITECTURE

Two-file shape. The plugin file is alias-only + an fpath nudge; the compdef file is the entire completion engine.

FileLinesRole
zsh-cargo-completion.plugin.zsh 23 Plugin entry. Declares 17 cargo aliases (co, cr, cb, cbr, ct, ccy, cfm, cfi, cfa, cad, ci, ciu, cs, cfe, cpa, cpl, ccl). Runs the Zsh Plugin Standard 0= header to resolve its own path, then prepends ${0:h}/src to fpath so compinit picks up src/_cargo.
src/_cargo 450 The completion. Starts with #compdef cargo, autoloads regexp-replace, defines __cargo_remote_packages (the live crates.io completer), _cargo (top-level dispatcher), and 8 helper-completion fns (_cargo_unstable_flags, _cargo_installed_crates, _cargo_cmds, _cargo_package_names, _cargo_names_from_array, _cargo_example_names, _cargo_test_names, _cargo_benchmark_names). The case ${words[1]} statement under _cargo dispatches to 32 per-subcommand arms (add, bench, build, check, clean, doc, fetch, fix, generate-lockfile, git-checkout, help, init, install, locate-project, login, metadata, new, owner, package, pkgid, publish, read-manifest, run, rustc, rustdoc, search, test, uninstall, update, verify-project, version, yank) — most wrapping an _arguments block with the subcommand's flag table, plus a wildcard *) fallthrough that probes for a user-defined _cargo-<sub> function before dropping to _default.
Total source 473 2 files · pure zsh · compsys-native

#TEST COVERAGE

172 @test blocks across 6 zunit files under tests/t-*.zsh. Plus 21 portable shell gates under tests/*.sh (final-newline, has-h1, has-body-tag, has-html-closing, no-deprecated-tags, no-placeholder-href, no-http-links, no-inline-handlers, target-blank-rel-noopener, man-page-synopsis-section, shell-shebang, shell-executable, workflow-no-tabs, readme-has-badges, ...) that run alongside the zunit suite across the docs-gates, polish-gates, semantic-gates, newline-gates, and structure-gates CI jobs.

FileTestsPins
t-aliases.zsh 21 Each of the 17 aliases resolves to the documented cargo invocation; fpath augmentation uses ${0:h}/src (plugin-manager portable); _cargo leads with #compdef cargo.
t-syntax.zsh 133 Every *.zsh in the repo root and every file under src/ parses cleanly under zsh -n. Largest test file by count — covers parse safety per-file, not just per-repo.
t-contract.zsh 3 Plugin-contract pins: entrypoint stem matches plugin dir basename, entrypoint parses under zsh -n, every _* completion file leads with #compdef.
t-contract2.zsh 5 OMZ-style install pins: plugins+=(zsh-cargo-completion) path works; fpath is prepended, not replaced.
t-contract3.zsh 5 Zinit-style install pins: zinit load path resolves; no compile-on-load hooks; nocompile ice honored.
t-contract4.zsh 5 Manual source path: standalone source from any CWD honors ${0:h} resolution; no global state leak before sourcing.
Total 172 6 zunit files · alias-surface + syntax + install-path-contract

/INTEGRATION

Zinit (recommended)

zinit ice lucid nocompile
zinit load MenkeTechnologies/zsh-cargo-completion
nocompile keeps the source path stable so ${0:h}/src resolves to the real on-disk src/ directory (not the compiled .zwc).

Oh My Zsh

Clone into $ZSH_CUSTOM/plugins/zsh-cargo-completion, then add to plugins=(...). OMZ sources zsh-cargo-completion.plugin.zsh, the file declares its aliases, augments fpath, and OMZ's own compinit picks up _cargo on the next prompt.

Cache layer (zsh built-in)

__cargo_remote_packages uses _retrieve_cache + _store_cache keyed by crate_${PREFIX}_cache. First TAB against a prefix fires cargo search; subsequent TABs on the same prefix hit the cache. Whether the on-disk tier is consulted at all is governed by zsh's standard zstyle ':completion:*' use-cache yes / cache-path styles — user-tunable. The cache has no TTL; remove $HOME/.zcompcache/crate_*_cache to force a fresh query.

OMZ plugin compatibility

The 17 aliases overlap intentionally with the OMZ rust / cargo plugins (co, cr, cb, ct, ...) — load order is "OMZ first, then this plugin" so the local aliases win, but the underlying cargo CLI shape is identical.

No daemon, no fork hot path

The only external process invocation is cargo search — gated behind a prefix length check (skipped if $PREFIX starts with -) and gated again behind the cache. Every other completion path (subcommand list via cargo --list, installed crates via cargo install --list, local package names) is also cached.

Public-callable helpers

The 8 helper fns are namespaced (_cargo_*) — user-defined completions and sibling plugins can reuse them. _cargo_installed_crates in particular is the answer to "complete the binary name for cargo uninstall / cargo install --force" — no zsh-cargo-completion-specific knowledge required to call it.


!DESIGN DECISIONS

Live cargo search, not a vendored crate index

A vendored crate index would go stale on day one. The completer shells out to cargo search — the same code path the user would run manually — so the result reflects the current published crates.io state. The cost is one network call per uncached prefix; the gain is a completion that never lies.

2-tier memoization: parameter + on-disk cache

The first cache tier is a zsh parameter (__crate_${PREFIX}) probed via $+param. The second is the standard _retrieve_cache / _store_cache on-disk cache. The parameter tier wins within a single shell session (no ~/.zcompcache stat); the on-disk tier wins across sessions.

Skip remote lookup on flag prefix

[[ "$PREFIX" == -* ]] && return 1 at the top of __cargo_remote_packages — when the user is in the middle of typing a flag (e.g. cargo add --quiet), the completer doesn't fire cargo search. Two seconds saved per accidental TAB on flags.

Subcommand list via cargo --list, not a hardcoded table

_cargo_cmds parses cargo --list output (after dropping the header and de-indenting), then feeds it to _describe. New custom subcommands (anything on $PATH matching cargo-*) appear in completion automatically — no plugin update required.

32 per-subcommand _arguments arms, not a single mega-arm

cargo's flag surface is split per subcommand. The completion mirrors that shape — cargo build flags don't leak into cargo install completions and vice versa. Cost: 450 lines of _cargo file. Gain: each TAB shows only the flags that the subcommand under cursor actually accepts.

Aliases live in the plugin file, not in the README

The 17 aliases ship as live alias commands in zsh-cargo-completion.plugin.zsh — the README is documentation, the plugin file is the source of truth. t-aliases.zsh pins both surfaces stay in sync.


@FOOTPRINT


$ALIAS REFERENCE

All 17 aliases are declared at the top of zsh-cargo-completion.plugin.zsh. Each is a literal alias command — the plugin file is the source of truth, mirrored by the README and pinned by t-aliases.zsh.

AliasExpansionNotes
cocargoBase command shorthand.
crcargo runRun the current project's default binary.
cbcargo buildDebug build.
cbrcargo build --releaseOptimized release build.
ctcargo testRun the test suite.
ccycargo clippyLint with clippy.
cfmcargo fmtFormat with rustfmt.
cficargo fixApply compiler-suggested fixes.
cfacargo fix --allow-dirty --allow-staged; cargo clippy --all-targets --fix -- -D warnings; cargo fmtOne-shot fix + clippy-fix + fmt chain. The only multi-command alias.
cadcargo addAdd a dependency — the live-completion entry point.
cicargo installInstall a binary crate — also live-completed.
ciucargo install-update -aUpdate all installed binary crates (requires cargo-update).
cscargo searchQuery crates.io from the shell — the same command the completer shells out to.
cfecargo fetchFetch dependencies without building.
cpacargo packageAssemble a publishable .crate tarball.
cplcargo publishPublish to crates.io.
cclcargo cleanRemove the target/ directory.

>REMOTE COMPLETER WALKTHROUGH

__cargo_remote_packages is the one function that touches the network. It is invoked from the add arm (positional) and the install arm (*: :__cargo_remote_packages). Step by step, top to bottom of the function body:

StepCodeEffect
1. Flag guard[[ "$PREFIX" == -* ]] && return 1If the word under cursor starts with - (a flag, not a crate name), bail before any network call.
2. Key derivationcrate_cache_file="crate_${PREFIX}_cache"
crate_ary="__crate_${PREFIX}"
Per-prefix on-disk cache key and per-prefix session parameter name.
3. Parameter proberet=$(eval "printf \$+$crate_ary" ...)Probe whether the session parameter __crate_${PREFIX} already exists ($+ = set-test). If set, reuse it (tier 1).
4. On-disk cacheif ! _retrieve_cache $crate_cache_fileOn a session miss, try the standard zsh on-disk completion cache (tier 2).
5. Live querycargo search --color=never --limit 1000 -q $PREFIXOn a cache miss, query crates.io. Up to 1000 results, no color codes, quiet.
6. Parse loopwhile read crate desc; do ... esacRead crate desc pairs; case drops the trailing ... "and N more" line. Each kept line becomes a quoted crate:desc pair via ${(q)...}.
7. Store_store_cache $crate_cache_file tmp_aryPopulate both the session parameter and the on-disk cache for next time.
8. Offer_describe -t remote-crate 'remote crate' tmp_aryFeed the crate:description pairs to compsys so each candidate shows its crates.io blurb.

%HELPER FUNCTION REFERENCE

8 namespaced _cargo_* helpers backing the per-subcommand arms. All are public-callable — sibling plugins and user completions can reuse them.

FunctionSourceBacks
_cargo_cmdsParses cargo --list (drop header, de-indent 4 spaces, split name/desc on whitespace) via parameter-expansion flags.Top-level subcommand completion (positional 1).
_cargo_unstable_flagsParses cargo -Z help, keeping --* lines.The -Z nightly-flag completer in common.
_cargo_installed_cratescompadd over the first column of cargo install --list.cargo uninstall crate argument.
_cargo_package_names_message -e packages package — currently a message stub (marked #FIXME: Disabled until fixed in source).Every -p/--package flag across build/check/clean/doc/run/rustc/rustdoc/test/etc.
_cargo_names_from_arrayReads cargo locate-project manifest path, scans [[block]] sections, extracts name = "..." via regexp-replace.Shared backend for test/bench name completion.
_cargo_example_namesLists examples/*.rs, strips path + .rs via :t:r.--example flags on build/install/run/test/etc.
_cargo_test_namesDelegates to _cargo_names_from_array "test".cargo test name + --test flag.
_cargo_benchmark_namesDelegates to _cargo_names_from_array "bench".--bench flag in the shared command_scope_spec.

~SHARED FLAG GROUPS

_cargo defines reusable _arguments spec arrays at the top of the function, then splices the relevant ones into each subcommand arm — so the same flag never drifts between subcommands.

common

Carried by every arm: -v/--verbose, -q/--quiet (mutually exclusive), -Z (unstable flags), --frozen, --locked, --color= (auto/always/never), -h/--help.

command_scope_spec

Mutually-exclusive target selectors: --bench, --example, --bin, --lib, --test. Spliced into bench/build/check/fix/rustc/rustdoc.

parallel / features

parallel = -j/--jobs. features = --features=, --all-features (exclusive), --no-default-features.

msgfmt / triple / target / manifest / registry

--message-format= (human/json/short), --target= triple, --target-dir=, --manifest-path=, --registry=. Each subcommand splices only the groups it accepts.

Top-level toolchain overrides

The dispatcher _arguments also completes +stable / +beta / +nightly (mutually exclusive), --list, --explain=, and -V/--version before the subcommand positional.

Plugin fallthrough

The wildcard *) arm calls _call_function ret _cargo-${words[1]} — any installed cargo-<sub> can ship its own _cargo-<sub> completer and have it picked up. Otherwise it falls back to _default.