[New] bash_completion: complete options and arguments in context

Parse words before the cursor once to offer flags, versions, and aliases
in the positions that accept them. Distinguish install options before
and after the version, and leave run and exec arguments to the shell.

Match local names literally. Account for Readline splitting at `=` and
quoting common prefixes. Give zsh the same candidates as raw strings so
its line editor can match, quote, and close arguments in its own syntax.

Check the offered flags against nvm help and cover argument boundaries,
including the actual arguments submitted by zsh after Tab completion.

Co-authored-by: Peter Dave Hello <hsu@peterdavehello.org>
Co-authored-by: Jordan Harband <ljharb@gmail.com>
This commit is contained in:
Peter Dave HelloandJordan Harband authored and Jordan Harband committed 2026-11-25 13:23:26 -08:00
1 parent 3bf6686090
commit bea27fbe0f
2 files changed
+525 -83

No files matched your search

+271 -83
View File
@@ -6,99 +6,265 @@ if ! command -v nvm &> /dev/null; then
return
fi
__nvm_generate_completion() {
declare current_word
declare word
declare glob_was_off
current_word="${COMP_WORDS[COMP_CWORD]}"
# not `compgen -W`: it expands every word (including command substitution),
# and the words include alias and version directory names
COMPREPLY=()
glob_was_off=false
case $- in
*f*) glob_was_off=true ;;
esac
set -f
for word in $1; do
case "${word}" in
"${current_word}"*) COMPREPLY+=("${word}") ;;
__nvm_complete() {
local candidate
# Match data literally: compgen -W would expand alias and directory names.
for candidate in "$@"; do
case "${candidate}" in
"${match_prefix}"*) COMPREPLY+=("${candidate}") ;;
esac
done
if [ "${glob_was_off}" = false ]; then
set +f
fi
return 0
}
__nvm_commands() {
declare current_word
declare command
current_word="${COMP_WORDS[COMP_CWORD]}"
COMMANDS='
help install uninstall use run exec
alias unalias reinstall-packages
current list ls list-remote ls-remote
install-latest-npm
cache deactivate unload
version version-remote which'
if [ ${#COMP_WORDS[@]} == 4 ]; then
command="${COMP_WORDS[COMP_CWORD - 2]}"
case "${command}" in
alias) __nvm_installed_nodes ;;
esac
else
case "${current_word}" in
-*) __nvm_options ;;
*) __nvm_generate_completion "${COMMANDS}" ;;
esac
fi
}
__nvm_options() {
OPTIONS=''
__nvm_generate_completion "${OPTIONS}"
}
__nvm_installed_nodes() {
__nvm_generate_completion "$(nvm_ls) $(__nvm_aliases)"
}
__nvm_aliases() {
declare aliases
aliases=""
if [ -d "${NVM_DIR}/alias" ]; then
aliases="$(command cd "${NVM_DIR}/alias" && command find "${PWD}" -type f | command sed "s:${PWD}/::")"
fi
echo "${aliases} node stable unstable iojs"
}
__nvm_alias() {
__nvm_generate_completion "$(__nvm_aliases)"
local file
if [ -d "${NVM_DIR}/alias" ]; then
# Not process substitution, which POSIX-mode bash 3 rejects.
while IFS= read -r file; do
if [ -n "${file}" ]; then __nvm_complete "${file#./}"; fi
done <<EOF
$(command cd "${NVM_DIR}/alias" && command find . -type f)
EOF
fi
__nvm_complete node stable unstable iojs
}
__nvm() {
declare previous_word
previous_word="${COMP_WORDS[COMP_CWORD - 1]}"
__nvm_installed_nodes() {
local version
while IFS= read -r version; do
case "${version}" in
'' | N/A) ;;
'system '*) __nvm_complete system ;;
*) __nvm_complete "${version}" ;;
esac
done <<EOF
$(nvm_ls 2>/dev/null)
EOF
__nvm_alias
}
case "${previous_word}" in
use | run | exec | ls | list | uninstall) __nvm_installed_nodes ;;
alias | unalias) __nvm_alias ;;
*) __nvm_commands ;;
esac
# Update the locals in __nvm_candidates from completed words only. A nonzero return
# hands completion back to the shell (e.g. for an exec command or a -j value).
__nvm_parse_context() {
local i word next rest
rest="${COMP_LINE-}"
rest="${rest#*"${COMP_WORDS[0]}"}"
rest="${rest#*"${subcommand}"}"
for (( i = 2; i < COMP_CWORD; i++ )); do
word="${COMP_WORDS[i]}"
rest="${rest#*"${word}"}"
# Readline splits --flag=value into --flag, =, value by default. Join
# adjacent pieces only: in "--flag= v20", v20 is a positional argument.
while (( i < COMP_CWORD )); do
next="${COMP_WORDS[i+1]}"
if [[ -z "${next}" ]]; then
# The word being completed is this option's value.
(( i + 1 < COMP_CWORD )) || [[ "${word}" != -*= || "${rest}" == [[:space:]]* ]] || return 1
break
fi
[[ "${rest}" == "${next}"* ]] || break
i=$((i + 1))
(( i < COMP_CWORD )) || return 1
word="${word}${next}"
rest="${rest#"${next}"}"
done
if (( end_options )); then
arg_count=$((arg_count + 1))
continue
fi
case "${subcommand}" in
run | exec)
case "${word}" in
--silent | --lts | --lts=* | --only | --only=*) ;;
*) return 1 ;;
esac
;;
esac
case "${word}" in
--)
case "${subcommand}" in
use) end_options=1; arg_count=0 ;;
ls | list | ls-remote | list-remote | version-remote | alias | which | deactivate) ;;
*) return 1 ;;
esac
;;
-j)
if [[ "${subcommand}" = install || "${subcommand}" = i ]]; then
i=$((i + 1))
(( i < COMP_CWORD )) || return 1
rest="${rest#*"${COMP_WORDS[i]}"}"
fi
;;
--only=*)
only=''
NVM_ONLY_SELECTED="${word#--only=}"
# Readline retains shell quotes; a category name cannot contain one.
NVM_ONLY_SELECTED="${NVM_ONLY_SELECTED//[\"\']/}"
;;
--only) only='' ;;
--lts | --lts=*) lts='' ;;
--no-alias) no_alias='' ;;
-s | -b) build_mode='' ;;
--save | -w) save='' ;;
--default | --alias=*) alias_target='' ;;
--reinstall-packages-from=* | --copy-packages-from=*) reinstall='' ;;
-*) ;;
*) arg_count=$((arg_count + 1)) ;;
esac
done
return 0
}
# complete is a bash builtin, but recent versions of ZSH come with a function
# called bashcompinit that will create a complete in ZSH. If the user is in
# ZSH, load and run bashcompinit before calling the complete function.
__nvm_options() {
local flags lts_flags="${lts}"
if [[ -z "${only}" && ",${NVM_ONLY_SELECTED}," != *,lts,* ]]; then
lts_flags=''
fi
case "${subcommand}" in
install | i)
flags="${only} --min= --no-progress --latest-npm --skip-default-packages ${save} ${alias_target} ${reinstall}"
if (( arg_count == 0 )); then
flags="${flags} ${build_mode} --offline ${lts_flags}"
fi
;;
uninstall | use)
flags="${only}"
if (( arg_count == 0 )); then flags="${flags} ${lts_flags}"; fi
if [ "${subcommand}" = use ]; then flags="${flags} --silent ${save}"; fi
;;
exec | run) flags="--silent ${lts_flags} ${only}" ;;
ls | list)
flags="--no-colors ${only}"
if (( arg_count == 0 )); then flags="${flags} ${no_alias}"; fi
;;
ls-remote | list-remote) flags="--no-colors --min= ${lts_flags} ${only}" ;;
version-remote) flags="--min= ${lts_flags} ${only}" ;;
alias) flags="--no-colors ${lts_flags} ${only}" ;;
which) flags="--silent ${only}" ;;
version | reinstall-packages | copy-packages) flags="${only}" ;;
deactivate) flags='--silent' ;;
*) return 0 ;;
esac
# Only split our fixed option lists, never user-supplied words.
local IFS=' '
# shellcheck disable=SC2086
__nvm_complete ${flags}
}
# Bash needs literal prefix filtering; zsh's compadd matches the candidates itself.
__nvm_candidates() {
if [[ -n ${ZSH_VERSION-} ]]; then emulate -L sh; fi
local current_word="${1}" match_prefix="${2-}"
COMPREPLY=()
if (( COMP_CWORD == 1 )); then
case "${current_word}" in
-*) __nvm_complete -h --help -v --version ;;
*)
__nvm_complete help install uninstall use run exec alias unalias \
reinstall-packages current list ls list-remote ls-remote install-latest-npm \
cache deactivate unload version version-remote which debug set-colors
;;
esac
return 0
fi
local subcommand="${COMP_WORDS[1]}"
case "${subcommand}" in
help | -h | --help | --no-colors)
if (( COMP_CWORD == 2 )); then
case "${subcommand}" in
--no-colors) __nvm_complete --help ;;
*) __nvm_complete --no-colors ;;
esac
fi
return 0
;;
esac
local arg_count=0 end_options=0
local only='--only=' lts='--lts --lts=' no_alias='--no-alias'
local build_mode='-s -b' save='--save' alias_target='--alias= --default' reinstall='--reinstall-packages-from='
local NVM_ONLY_SELECTED="${NVM_ONLY_SELECTED-}"
__nvm_parse_context || return 0
if (( ! end_options )); then
case "${current_word}" in
-*=*) return 0 ;;
-*) __nvm_options; return 0 ;;
esac
fi
case "${subcommand}" in
alias)
case "${arg_count}" in
0) __nvm_alias ;;
1) __nvm_installed_nodes ;;
esac
;;
unalias) if (( arg_count == 0 )); then __nvm_alias; fi ;;
cache) if (( arg_count == 0 )); then __nvm_complete dir clear; fi ;;
use | run | exec | uninstall)
if (( arg_count == 0 )) && [ -n "${lts}" ]; then
if [ "${subcommand}" != uninstall ]; then __nvm_complete current; fi
__nvm_installed_nodes
fi
;;
ls | list)
if (( arg_count == 0 )); then
if [ -n "${no_alias}" ]; then
__nvm_installed_nodes
elif (( ! end_options )); then
__nvm_options
fi
fi
;;
which | version | reinstall-packages | copy-packages)
if (( arg_count == 0 )); then
if [ "${subcommand}" = which ]; then __nvm_complete current; fi
__nvm_installed_nodes
fi
;;
esac
return 0
}
__nvm() {
local current_word="${2-${COMP_WORDS[COMP_CWORD]}}"
if [[ "${current_word}" == *\\* && "${COMP_WORDS[COMP_CWORD]}" == "${current_word}"* ]]; then
# Readline returns the escapes it inserted for an unquoted common prefix.
# shellcheck disable=SC2162
IFS= read current_word <<< "${current_word}" || :
fi
__nvm_candidates "${current_word}" "${current_word}"
}
__nvm_complete_command() {
__nvm "$@"
local i quoted single_quote_escape="'\\''" history_escape="\"'!'\""
for (( i = 0; i < ${#COMPREPLY[@]}; i++ )); do
# Quote for the argument Readline is inserting into, not as a path:
# a same-named directory must not add a slash to an alias.
quoted="${COMPREPLY[i]}"
case "${COMP_WORDS[COMP_CWORD]:0:1}" in
"'") quoted="${quoted//\'/${single_quote_escape}}" ;;
'"')
quoted="${quoted//\\/\\\\}"
quoted="${quoted//\"/\\\"}"
quoted="${quoted//\$/\\\$}"
quoted="${quoted//\`/\\\`}"
quoted="${quoted//\!/${history_escape}}"
;;
*) printf -v quoted '%q' "${quoted}" ;;
esac
COMPREPLY[i]="${quoted}"
done
# Bash 3 has no compopt, so there a lone --flag= is followed by a space.
if (( ${#COMPREPLY[@]} == 1 && BASH_VERSINFO[0] >= 4 )) && [[ "${COMPREPLY[0]}" == -*= ]]; then
builtin compopt -o nospace 2>/dev/null || :
fi
}
# Keep Bash-compatible completion functions available to zsh callers.
if [[ -n ${ZSH_VERSION-} ]]; then
# First calling compinit (only if not called yet!)
# and then bashcompinit as mentioned by zsh man page.
@@ -110,6 +276,28 @@ if [[ -n ${ZSH_VERSION-} ]]; then
fi
fi
autoload -U +X bashcompinit && bashcompinit
fi
# ZLE supplies words, CURRENT, and PREFIX when it invokes the completer.
# shellcheck disable=SC2154
__nvm_zsh_complete() {
local COMP_CWORD=$((CURRENT - 1)) COMP_LINE="${words[*]}"
local -a COMP_WORDS COMPREPLY value_flags arguments
COMP_WORDS=("${words[@]}")
__nvm_candidates "${PREFIX}"
complete -o default -F __nvm nvm
local word ret=1
for word in "${COMPREPLY[@]}"; do
case "${word}" in
-*=) value_flags+=("${word}") ;;
*) arguments+=("${word}") ;;
esac
done
# Only option values need an explicit suffix. For everything else let
# the line editor match, quote, and close the argument before adding a space.
compadd -S '' -a value_flags && ret=0
compadd -a arguments && ret=0
(( ret == 0 )) || _default
}
compdef __nvm_zsh_complete nvm
else
complete -o default -F __nvm_complete_command nvm
fi
+254
View File
@@ -0,0 +1,254 @@
#!/bin/sh
# shellcheck shell=bash
# bash_completion targets bash and zsh; zsh is driven through zpty below.
{ [ -n "${BASH_VERSION-}" ] && ! shopt -oq posix; } || exec bash "$0" "$@"
set -e
set -o pipefail
die() { printf '%s\n' "$*" >&2; exit 1; }
root="$(cd "$(dirname "$0")/../../.." && pwd)"
NVM_DIR="$(mktemp -d)"
export NVM_DIR
# Under bash 3.2's set -e, a fatal error runs this trap with $? = 0.
trap 'rm -rf "${NVM_DIR}"; [ -n "${finished-}" ]' EXIT
# shellcheck disable=SC1091
. "${root}/nvm.sh" --no-use
# shellcheck disable=SC1091
. "${root}/bash_completion"
[ "$(complete -p nvm)" = 'complete -o default -F __nvm_complete_command nvm' ] \
|| die "unexpected registration: $(complete -p nvm)"
complete_for() {
COMP_WORDS=("$@")
COMP_CWORD=$(( $# - 1 ))
COMPREPLY=(stale)
__nvm
}
replies() { printf '%s\n' "${COMPREPLY[@]}" | LC_ALL=C sort -u; }
expect() {
local actual expected
actual="$(replies)"
expected="$(printf '%s\n' "$@" | LC_ALL=C sort -u)"
[ "${actual}" = "${expected}" ] || die "${COMP_WORDS[*]}: expected [${expected}], got [${actual}]"
}
# Check the public completion entry point, not a second inventory of options.
usage="$(nvm --help --no-colors | awk '
/^Usage:/ { usage = 1; next }
/^Example:/ { usage = 0 }
!usage { next }
/^ nvm / {
cmd = $2
print cmd
if ($3 !~ /^-/) next
flag = $3
}
/^ -/ { flag = $1 }
flag { sub(/=.*/, "=", flag); print cmd, flag; flag = "" }
')"
[[ "${usage}" == *'install --offline'* ]] || die 'did not find install options in nvm --help'
for cmd in $(printf '%s\n' "${usage}" | awk 'NF == 1' | sort -u); do
complete_for nvm "${cmd}"
printf '%s\n' "${COMPREPLY[@]}" | grep -Fx -- "${cmd}" >/dev/null || die "missing command ${cmd}"
complete_for nvm "${cmd}" -
expected="$(printf '%s\n' "${usage}" | awk -v cmd="${cmd}" 'NF == 2 && $1 == cmd { print $2 }' | LC_ALL=C sort -u)"
[ "$(replies)" = "${expected}" ] || die "${cmd} options differ from help: expected [${expected}], got [$(replies)]"
done
mkdir -p "${NVM_DIR}/alias"
: > "${NVM_DIR}/alias/team node"
: > "${NVM_DIR}/alias/reader's node"
: > "${NVM_DIR}/alias/shared build-alpha"
: > "${NVM_DIR}/alias/shared build-beta"
nvm_ls() {
case "${NVM_ONLY_SELECTED-}" in
alpha) printf '%s\n' v27.0.0-alpha.1 ;;
*) printf '%s\n' v22.0.0 'system v20.0.0' ;;
esac
}
complete_for nvm alias --no-colors team
expect 'team node'
__nvm_complete_command nvm team --no-colors
expect 'team\ node'
COMP_WORDS=(nvm alias '"te')
COMP_CWORD=2
__nvm_complete_command nvm te alias
expect 'team node'
COMP_WORDS=(nvm alias "'rea")
__nvm_complete_command nvm rea alias
expect "reader'\\''s node"
COMP_WORDS=(nvm alias sha)
__nvm_complete_command nvm sha alias
expect 'shared\ build-alpha' 'shared\ build-beta'
COMP_WORDS[2]='shared\ build-'
__nvm_complete_command nvm "${COMP_WORDS[2]}" alias
expect 'shared\ build-alpha' 'shared\ build-beta'
complete_for nvm alias --no-colors my-team v
expect v22.0.0
complete_for nvm use --silent sys
expect system
complete_for nvm which cur
expect current
complete_for nvm cache c
expect clear
complete_for nvm cache -- cl
expect
complete_for nvm current ''
expect
complete_for nvm --no-colors --h
expect --help
complete_for nvm de
expect debug deactivate
complete_for nvm use te
expect 'team node'
complete_for nvm use cur
expect current
complete_for nvm uninstall cur
expect
complete_for nvm unalias te
expect 'team node'
complete_for nvm alias my-team no
expect node
complete_for nvm ls ''
expect v22.0.0 system 'team node' "reader's node" 'shared build-alpha' 'shared build-beta' node stable unstable iojs
complete_for nvm use -- --si
expect
COMP_LINE='nvm install --reinstall-packages-from=node --re' complete_for nvm install --reinstall-packages-from = node --re
expect
: > "${NVM_DIR}/alias/odd\$HOME\`x\`!"
COMP_WORDS=(nvm unalias '"odd')
COMP_CWORD=2
__nvm_complete_command nvm odd unalias
# shellcheck disable=SC2016
expect 'odd\$HOME\`x\`"'"'"'!'"'"'"'
COMP_WORDS=(nvm unalias odd)
__nvm_complete_command nvm odd unalias
# shellcheck disable=SC2016
expect 'odd\$HOME\`x\`\!'
command rm "${NVM_DIR}/alias/odd\$HOME\`x\`!"
complete_for nvm ls --no-alias ''
expect --no-colors --only=
complete_for nvm list v22 --no
expect --no-colors
complete_for nvm ls -- --no-a
expect --no-alias
complete_for nvm install -j --of
expect
complete_for nvm i -j 4 --of
expect --offline
complete_for nvm install 22 -
expect --only= --min= --no-progress --latest-npm --skip-default-packages --save --alias= --default --reinstall-packages-from=
complete_for nvm install -s -b
expect
complete_for nvm install -w --sa
expect
complete_for nvm uninstall --lts --on
expect --only=
complete_for nvm uninstall v22 --lts
expect
complete_for nvm use -- v
expect v22.0.0
for cmd in run exec; do
complete_for nvm "${cmd}" --silent v
expect v22.0.0
complete_for nvm "${cmd}" --lts v
expect
complete_for nvm "${cmd}" v22 --si
expect
complete_for nvm "${cmd}" -- --si
expect
done
complete_for nvm install 22 -- --min
expect
# Real Readline splits versus a customized COMP_WORDBREAKS or bashcompinit.
COMP_LINE='nvm use --only=alpha v' complete_for nvm use --only = alpha v
expect v27.0.0-alpha.1
COMP_LINE='nvm use --only="alpha" v' complete_for nvm use --only = '"alpha"' v
expect v27.0.0-alpha.1
complete_for nvm use --only=alpha v
expect v27.0.0-alpha.1
complete_for nvm use --only=non-lts --l
expect
complete_for nvm use --only=non-lts,lts --l
expect --lts --lts=
COMP_LINE='nvm install --alias=dev --of' complete_for nvm install --alias = dev --of
expect --offline
COMP_LINE='nvm install --alias=dev --de' complete_for nvm install --alias = dev --de
expect
COMP_LINE='nvm install --alias= 22 --of' complete_for nvm install --alias = 22 --of
expect
COMP_LINE='nvm install --alias dev --of' complete_for nvm install --alias dev --of
expect
COMP_LINE='nvm use --only=al' complete_for nvm use --only = al
expect
COMP_LINE='nvm which --only=' complete_for nvm which --only = ''
expect
COMP_LINE='nvm use --lts=' complete_for nvm use --lts = ''
expect
COMP_LINE='nvm use --only= ' complete_for nvm use --only = ''
expect current v22.0.0 system 'team node' "reader's node" 'shared build-alpha' 'shared build-beta' node stable unstable iojs
# Only real values, even where Bash 3 cannot suppress the space after '='.
COMP_WORDS=(nvm install --al)
COMP_CWORD=2
__nvm_complete_command nvm --al install
expect --alias=
set -o posix
complete_for nvm use --silent v
expect v22.0.0
complete_for nvm unalias te
expect 'team node'
set +o posix
POSIXLY_CORRECT=1 bash -c '. "$1/nvm.sh" --no-use && . "$1/bash_completion"' - "${root}" \
|| die 'bash_completion cannot be sourced in POSIX mode'
# Bash passes the prefix up to the cursor as $2, even with more words to its right.
COMP_WORDS=(nvm use --silent v22)
COMP_CWORD=2
COMPREPLY=(stale)
__nvm nvm --si use
expect --silent
if command -v zsh >/dev/null; then
: > "${NVM_DIR}/alias/team\"quoted\""
: > "${NVM_DIR}/alias/team\\path"
# ZLE quotes common prefixes and closes quoted arguments. Check the argv
# delivered after Tab and Enter, not just the candidate strings.
actual="$(ZDOTDIR="${NVM_DIR}" ZSH_DISABLE_COMPFIX=true TERM=xterm \
NVM_TEST_COMPLETION="${root}/bash_completion" zsh -f <<'ZSH'
zmodload zsh/zpty || exit 1
# An unclosed quote would leave the inner shell waiting for input forever.
{ sleep 60; kill -KILL $$; } >/dev/null 2>&1 &!
watchdog=$!
zpty terminal env TMOUT=10 zsh -f -i || exit 1
trap 'zpty -d terminal' EXIT
zpty -w terminal 'nvm() { { printf "<%s>" "$@"; echo; } >> "$NVM_DIR/zsh-argv"; }; . "$NVM_TEST_COMPLETION" || exit 1; printf "ready:%s\n" nvm'
zpty -r -m terminal line '*ready:nvm*' || exit 1
zpty -w terminal $'nvm --no-colors \t'
zpty -w terminal $'nvm alias team\\"q\t'
zpty -w terminal $'nvm alias sha\ta\t'
zpty -w terminal $'nvm alias "team\\p\tnext'
zpty -w terminal $'nvm install --onl\tlts'
zpty -w terminal exit
zpty -r terminal >/dev/null
cat "$NVM_DIR/zsh-argv"
kill $watchdog
ZSH
)" || die 'could not run the interactive zsh completion test'
expected="$(printf '%s\n' '<--no-colors><--help>' '<alias><team"quoted">' '<alias><shared build-alpha>' '<alias><team\path><next>' '<install><--only=lts>')"
[ "${actual}" = "${expected}" ] || die "zsh: expected [${expected}], got [${actual}]"
fi
finished=1