The easy way in this specific case: make it an alias instead. This is possible because you can put --ask
before the network name. Zsh expands aliases before doing completion by default.
alias cn='nmcli device wifi connect --ask'
If you use a function, you need to teach zsh about the arguments of the function: specify a completion function for cn
, which may or may not be a custom function depending on what it has to do. (I assume that you're using the “new completion system”, i.e. you have compinit
in your .zshrc
.)
Here the function is a simple wrapper around another command. So see how this command's arguments are completed.
% echo $_comps[nmcli]
_networkmanager
For most commands, the name of the completion function is the command name with an underscore before it, but for nmcli
, in recent zsh versions, it's a different name. (It may be _nmcli
on your system if you're running zsh <5.5.) Next, look at the source code to see how the function works. See How to look up zsh completion definitions for more information.
You don't need to understand everything (and good luck trying: the completion system is complex!) but for most commands it's reasonably easy to figure out how a specific subcommand or option is completed. In zsh ≥5.5 it's the function _nm_device_wifi_connect
which in turn calls _nm_device_wifi_ssids
. In zsh ≤5.4 I think _nmcli
doesn't support this particular command line syntax (the syntax of nmcli
keeps changing, so by the time zsh releases a version, its nmcli
completion code tends to be already out of date).
With zsh ≥5.5, you can associate _nm_device_wifi_ssids
with cn
. However, there's a twist: if you first complete cn
without having ever completed nmcli
, zsh won't know where to find _nm_device_wifi_ssids
, because completion functions are loaded on demand and this mechanism only knows how to find the main function _networkmanager
, not auxiliary functions like _nm_XXX
. See Can I use a helper function from a ZSH completion file in another and overwrite and reuse existing function in zsh for how to work around this.
Here the code of the zsh 5.5 function is simple, and zsh 5.4 doesn't have a corresponding function anyway. So the easiest solution is to copy the relevant part of the zsh 5.5 code into a new function.
function _cn {
compadd -- ${(f)"$(_call_program nmcli nmcli -t -f ssid device wifi list)"}
}
compdef `_cn` cn