1 # bash completion support for xkbcli.
3 # See completion API documentation: https://github.com/scop/bash-completion
4 # NOTE: The script parses the commands help messages to provide the completions,
5 # thus any new subcommand or option will be supported, as long as it has its
6 # entry in the help messages. This should result in low maintenancei effort.
10 # Initialization: https://github.com/scop/bash-completion/blob/fdf4456186eb4548ef628e65fb1be73d8e4695e9/bash_completion.d/000_bash_completion_compat.bash#L205
11 local cur prev words cword cmd
12 _init_completion -s || return
16 while [[ "$i" -lt "$COMP_CWORD" ]]; do
17 local s="${COMP_WORDS[i]}"
28 # Parse available subcommands
30 local is_command_list=false
32 while IFS='' read -r line; do
33 # Traverse subcommand list
34 if [[ "$is_command_list" == true ]]; then
35 # Check for subcommand based on the indentation
36 if [[ "$line" =~ ^[[:blank:]]{2}([[:alpha:]]([[:alnum:]]|-)+)$ ]]; then
37 subcommands+=("${BASH_REMATCH[1]}")
38 # Detect end of subcommand list based on indentation
39 elif [[ "$line" =~ ^[[:graph:]] ]]; then
42 # Detect start of subcommand list
43 elif [[ "$line" == "Commands:" ]]; then
46 # NOTE: <( COMMAND ) Bash construct is “process substitution”.
47 done < <(xkbcli --help)
49 # No previous subcommand or incomplete: completion for root xkbcli command
50 if [[ "$i" -eq "$COMP_CWORD" ]]; then
52 # Doc for _parse_help: https://github.com/scop/bash-completion/blob/fdf4456186eb4548ef628e65fb1be73d8e4695e9/bash_completion.d/000_bash_completion_compat.bash#L311
53 opts=$(_parse_help xkbcli)
54 local cur="${COMP_WORDS[COMP_CWORD]}"
55 COMPREPLY=($(compgen -W "${subcommands[*]} $opts" -- "$cur"))
59 # Found a supported subcommand: proceed to completion
60 if [[ "${subcommands[*]}" =~ (^| )$cmd( |$) ]]; then
61 ___xkbcli_subcommand "$cmd"
65 ___xkbcli_subcommand()
69 compile-keymap | interactive-evdev)
70 case ${COMP_WORDS[COMP_CWORD-1]} in
77 if [[ ${COMP_WORDS[COMP_CWORD]} != -* ]]; then
84 # Parse help to get command options
86 # Doc for _parse_usage and _parse_help:
87 # • https://github.com/scop/bash-completion/blob/fdf4456186eb4548ef628e65fb1be73d8e4695e9/bash_completion.d/000_bash_completion_compat.bash#L335
88 # • https://github.com/scop/bash-completion/blob/fdf4456186eb4548ef628e65fb1be73d8e4695e9/bash_completion.d/000_bash_completion_compat.bash#L311
89 # We need both as the current help messages adopt both GNU and BSD styles.
90 opts=$(_parse_usage xkbcli "$1 --help")
91 opts+=$(_parse_help xkbcli "$1 --help")
92 local cur="${COMP_WORDS[COMP_CWORD]}"
93 COMPREPLY=($(compgen -W "$opts" -- "$cur"))
96 complete -F ___xkbcli_main xkbcli