|
3 | 3 | # AUTOCOMPLETION FOR ZSH
|
4 | 4 | # Reference: https://zsh.sourceforge.io/Doc/Release/Completion-Widgets.html
|
5 | 5 |
|
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 {})" |
10 | 15 |
|
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` |
12 | 20 | declare -A opts
|
13 | 21 |
|
14 | 22 | # Create associative array with key same as its value
|
15 | 23 | # 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 |
18 | 24 | 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") |
21 | 28 | 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. |
24 | 32 | compadd -Qa opts
|
0 commit comments