@@ -59,7 +59,10 @@ __%[1]s_get_completion_results() {
59
59
# Prepare the command to request completions for the program.
60
60
# Calling ${words[0]} instead of directly %[1]s allows handling aliases
61
61
args=("${words[@]:1}")
62
- requestComp="${words[0]} %[2]s ${args[*]}"
62
+ requestComp="${words[0]} %[2]s"
63
+ if [[ "${#args[@]}" -gt 0 ]]; then
64
+ requestComp+="$(printf " %%q" "${args[@]}")"
65
+ fi
63
66
64
67
lastParam=${words[$((${#words[@]}-1))]}
65
68
lastChar=${lastParam:$((${#lastParam}-1)):1}
@@ -224,15 +227,24 @@ __%[1]s_handle_completion_types() {
224
227
# completions at once on the command-line we must remove the descriptions.
225
228
# https://github.com/spf13/cobra/issues/1508
226
229
local tab=$'\t' comp
227
- while IFS='' read -r comp; do
230
+ local matches=()
231
+ for comp in "${completions[@]}"; do
228
232
[[ -z $comp ]] && continue
229
233
# Strip any description
230
234
comp=${comp%%%%$tab*}
231
235
# Only consider the completions that match
232
236
if [[ $comp == "$cur"* ]]; then
233
- COMPREPLY+=("$comp")
234
- fi
235
- done < <(printf "%%s\n" "${completions[@]}")
237
+ # Strictly speaking we could append directly to COMPREPLY here.
238
+ # But there's a pretty big performance hit involved with
239
+ # creating one subshell to printf %%q for each completion that
240
+ # matches. Instead, batch all the matches up so we can quote
241
+ # them all at once in a single printf call.
242
+ matches+=( "$comp" )
243
+ fi
244
+ done
245
+ while IFS='' read -r comp; do
246
+ COMPREPLY+=( "$comp" )
247
+ done < <(printf "%%q\n" "${matches[@]}")
236
248
;;
237
249
238
250
*)
@@ -247,7 +259,12 @@ __%[1]s_handle_standard_completion_case() {
247
259
248
260
# Short circuit to optimize if we don't have descriptions
249
261
if [[ "${completions[*]}" != *$tab* ]]; then
250
- IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")
262
+ # compgen's -W option respects shell quoting, so we need to escape.
263
+ local compgen_words="$(printf "%%q\n" "${completions[@]}")"
264
+ # compgen appears to respect shell quoting _after_ checking whether
265
+ # they have the right prefix, so we also need to quote cur.
266
+ local compgen_cur="$(printf "%%q" "${cur}")"
267
+ IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${compgen_words}" -- "${compgen_cur}")
251
268
return 0
252
269
fi
253
270
@@ -271,7 +288,7 @@ __%[1]s_handle_standard_completion_case() {
271
288
__%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
272
289
comp="${COMPREPLY[0]%%%%$tab*}"
273
290
__%[1]s_debug "Removed description from single completion, which is now: ${comp}"
274
- COMPREPLY[0]=$ comp
291
+ COMPREPLY[0]="$(printf "%%q" "${ comp}")"
275
292
else # Format the descriptions
276
293
__%[1]s_format_comp_descriptions $longest
277
294
fi
0 commit comments