Skip to content

Commit 65cf677

Browse files
committed
Fix zsh completion when worktree names have spaces
1 parent e3f8e44 commit 65cf677

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

completions/_wt_completion

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,30 @@
33
# AUTOCOMPLETION FOR ZSH
44
# Reference: https://zsh.sourceforge.io/Doc/Release/Completion-Widgets.html
55

6-
# wt list: list all the available worktrees
7-
# | awk '{ print $1; }': grab the first column of the output
8-
# | tr "\n" " ": replace line break character with space to put the worktrees on single line
9-
# separated by space
6+
# `list` is populated with the names of all Git worktrees in the current directory.
7+
# git rev-parse --git-dir: Check if the current directory is a Git repository.
8+
# git worktree list --porcelain: List all worktrees in an easily parse-able way.
9+
# awk '/^worktree / { sub("worktree ", ""); print; }': Extract the worktree names and remove the `worktree ` prefix.
10+
# xargs -I{} basename {}: Get the base name of each worktree path, preserving whitespace.
11+
list="$(git rev-parse --git-dir &> /dev/null \
12+
&& git worktree list --porcelain \
13+
| awk '/^worktree / { sub("worktree ", ""); print; }' \
14+
| xargs -I{} basename {})"
1015

11-
list="$(wt list | awk '{ print $1; }' | tr "\n" " ")"
16+
# Split the output into an array, line-by-line.
17+
list=("${(@f)${list}}")
18+
19+
# Declare an associative array named `opts`
1220
declare -A opts
1321

1422
# Create associative array with key same as its value
1523
# Completion keywords are taken as keys of arrays and the possible matches are their values
16-
# shwordsplit: iterate over a string separated by space (like sh/bash)
17-
setopt shwordsplit
1824
for item in $list; do
19-
base="$(basename -- "$item")"
20-
opts+=(["$base"]="$base")
25+
# Escape every element's special characters
26+
item=$(printf '%q' "$item")
27+
opts+=(["$item"]="$item")
2128
done
22-
unsetopt shwordsplit
23-
29+
# Add the keys of `opts` as completion options for the `wt` command.
30+
# `-Q` quotes the completion options.
31+
# `-a` specifies that the options are taken from an associative array.
2432
compadd -Qa opts

0 commit comments

Comments
 (0)