Zsh’s autocompletion options from variable
1
vote
1
answer
71
views
## General overview
I have to set a values auto-completion in zsh for a command (in the following minimal example, I will show it with
testcmd
).
So my current code work quiet well with hardcoded values:
#### Current auto-completion code (the one who works)
function testcmd()
{
echo "Nothing to do, just a test command"
}
_test_complete() {
_values \
"Possible values" \
foo'[Foo]' \
bar'[Bar baz]' \
}
compdef _test_complete testcmd
#### Current auto-completion behavior
When I type testcmd
, I correctly get the following desired rendering:
$ testcmd
Possible values
bar -- Bar baz
foo -- Foo
## What is the goal I search to reach
But as you see, the values are hard-coded inside the function, ideally, the function should retrieve them from a variable.
## What I already try
So naturaly, I put the values inside the variable values_variable
as following:
#### The tried code (the one who doesn’t works)
function testcmd()
{
echo "Nothing to do, just a test command"
}
_test_complete() {
local values_variable
values_variable="foo'[Foo]' \
bar'[Bar baz]' \ "
_values \
"Possible values" \
${values_variable}
}
compdef _test_complete testcmd
#### The behavior of the tried code
But then, when I try testcmd
it completely fail:
$ testcmd
_values:compvalues:11: invalid value definition: foo'[Foo]' \t\tbar'[Bar baz]' \
_values:compvalues:11: invalid value definition: foo'[Foo]' \t\tbar'[Bar baz]' \
_values:compvalues:11: invalid value definition: foo'[Foo]' \t\tbar'[Bar baz]' \
$ testcmd
### What I _also_ did
- I tried to escape the spaces with echo ${values_variable} | sed "s/ /\\ /g"
;
- I tried to use $values_variable
with the eval
command to pretend as if it content was directly typed inside the _values
definition ;
- I tried both eval
and escaping with eval $(echo ${values_variable} | sed "s/ /\\ /g")
;
- I tried to eveal line by line with a loop :
echo "$values_variable" | while read -r line; do
eval "$line"
done
- Expansion with ${(@f)values_variable}̀
;
- Many other ideas.
But it also failed.
### The nearest solution I found
In [_How to pass the contents of a file using cat
to _values
(zsh completion)_](https://stackoverflow.com/questions/21356370/how-to-pass-the-contents-of-a-file-using-cat-to-values-zsh-completion) tread I found a solution for values imported from an external file, but the user seems to be fronted to the same space escape problem. However, I can’t adjust it to the case with the $values_variables
internal variable.
I naturally tried this one, who doesn’t works either:
_test_complete() {
local values_variable
values_variable="foo'[Foo]' \
bar'[Bar baz]' \ "
OLD_IFS=$IFS
IFS=$'\n'
_values \
"Possible values" \
${values_variable}
IFS=$OLD_IFS
}
## The question
How can I load the values to give to _values
inside auto-completion function from a variable?
Asked by fauve
(1529 rep)
Feb 2, 2025, 05:54 PM
Last activity: Feb 3, 2025, 07:10 PM
Last activity: Feb 3, 2025, 07:10 PM