aopt_shell/script/
zsh.rs

1use super::Generator;
2
3use crate::acore::Error;
4use crate::SHELL_ZSH;
5
6#[derive(Debug, Clone, Copy, Default)]
7pub struct Zsh;
8
9impl Generator for Zsh {
10    type Err = Error;
11
12    fn is_avail(&self, name: &str) -> bool {
13        name == SHELL_ZSH
14    }
15
16    fn generate(&self, name: &str, bin: &str) -> Result<String, Self::Err> {
17        let template = r#"#compdef NAME
18
19function __complete_handler_NAME() {
20    local curr prev index cword
21
22    cword=${#words[@]}
23    index=$CURRENT
24    curr="${words[$index]}"
25    prev="${words[$index - 1]}"
26
27    local completions=("${(@f)$(PROGRAM --_shell SHELL --_curr "$curr" --_prev "$prev" "${words[@]}")}")
28
29    if [[ -n $completions ]]; then
30        _describe 'values' completions
31    else
32        _files
33    fi
34}
35
36if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
37  # autoload from fpath, call function directly, not sure how it works
38    __complete_handler_NAME "$@"
39else
40  # eval/source/. command, register function for later
41    compdef __complete_handler_NAME PROGRAM
42fi
43"#;
44
45        Ok(template
46            .replace("NAME", name)
47            .replace("PROGRAM", bin)
48            .replace("SHELL", SHELL_ZSH))
49    }
50}