Skip to content

Commit 2dbc88d

Browse files
scopsharkdp
authored andcommitted
Improve bash completion escaping
`compopt -o filenames` is a cheap way to accomplish mostly wanted behavior. However it is semantically incorrect when we are not actually completing filenames, and has side effects -- for example adds a trailing slash to candidates matching present dirs. bash >= 4.1 can `printf -v` to an array index, use it instead where available.
1 parent 66edfe5 commit 2dbc88d

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

assets/completions/bat.bash.in

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,27 @@ __bat_init_completion()
1010
_get_comp_words_by_ref "$@" cur prev words cword
1111
}
1212

13+
__bat_escape_completions()
14+
{
15+
# Do not escape if completing a quoted value.
16+
[[ $cur == [\"\']* ]] && return 0
17+
# printf -v to an array index is available in bash >= 4.1.
18+
# Use it if available, as -o filenames is semantically incorrect if
19+
# we are not actually completing filenames, and it has side effects
20+
# (e.g. adds trailing slash to candidates matching present dirs).
21+
if ((
22+
BASH_VERSINFO[0] > 4 || \
23+
BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] > 0
24+
)); then
25+
local i
26+
for i in ${!COMPREPLY[*]}; do
27+
printf -v "COMPREPLY[i]" %q "${COMPREPLY[i]}"
28+
done
29+
else
30+
compopt -o filenames
31+
fi
32+
}
33+
1334
_bat() {
1435
local cur prev words cword split=false
1536
if declare -F _init_completion >/dev/null 2>&1; then
@@ -45,7 +66,7 @@ _bat() {
4566
printf "%s\n" "$lang"
4667
done
4768
)" -- "$cur"))
48-
compopt -o filenames # for escaping
69+
__bat_escape_completions
4970
return 0
5071
;;
5172
-H | --highlight-line | \
@@ -92,7 +113,7 @@ _bat() {
92113
--theme)
93114
local IFS=$'\n'
94115
COMPREPLY=($(compgen -W "$("$1" --list-themes)" -- "$cur"))
95-
compopt -o filenames # for escaping
116+
__bat_escape_completions
96117
return 0
97118
;;
98119
--style)

0 commit comments

Comments
 (0)