简体   繁体   English

执行主类时如何使 bash 自动完成 java 限定的类名

[英]How can I make bash auto-complete java qualified class names when executing a main class

It's tedious to manually type in a class name for a java main class, especially in a deep package structure.手动输入 java 主类的类名很乏味,尤其是在深包结构中。 I would like bash tab-completion to autocomplete class names based on the directory structure of the class.我希望 bash tab-completion 根据类的目录结构自动完成类名。

How can I customize bash to do this?我如何自定义 bash 来做到这一点?

(I have added my own solution but I will accept a better answer.) (我已经添加了我自己的解决方案,但我会接受更好的答案。)

The bash builtin command complete can be used to customize tab-completion in bash. bash 内置命令complete可用于自定义 bash 中的制表符补全。

See bash documentation for more info.有关更多信息,请参阅bash 文档

Briefly, this can be done by specifying a custom completion function for java, complete -F _comp_java java .简而言之,这可以通过为 java 指定一个自定义完成函数来完成, complete -F _comp_java java The function can then use the variables COMP_WORDS and COMP_CWORD to access the words (and current word index) in a command line to generate a list of possible completions.然后,该函数可以使用变量 COMP_WORDS 和 COMP_CWORD 访问命令行中的单词(和当前单词索引)以生成可能完成的列表。 The possible completions must be placed in the array COMPREPLY.可能的补全必须放在数组 COMPREPLY 中。 The compgen builtin can be combined with the output of the ls command to find all paths that begin with the current word. compgen内置命令可以与ls命令的输出结合以查找以当前单词开头的所有路径。 These possible completions can then be modified to replace slashes with dots.然后可以修改这些可能的补全以用点替换斜线。

Here is one way to do this.这是执行此操作的一种方法。 Any cleaner solutions will be accepted.任何更清洁的解决方案都将被接受。

_comp_java () {
    prev=${COMP_WORDS[$COMP_CWORD - 1]}

    case $prev in
        "-jar")
            COMPREPLY=($(compgen -A file -- ${COMP_WORDS[$COMP_CWORD]}))
            ;;
        *)
            fields=($(echo ${COMP_WORDS[$COMP_CWORD]} | tr "." "\n"));
            [ "${COMP_WORDS[$COMP_CWORD]: -1}" == "." ] && lastIdx=0 || lastIdx=1
            [ ${#COMP_WORDS[$COMP_CWORD]} -eq 0 ] || [ ${lastIdx} -eq 0 ] && lastWord='' || lastWord=${fields[${#fields[@]}-1]}
            [ ${#COMP_WORDS[$COMP_CWORD]} -eq 0 ] && fields=() || fields=($(echo ${fields[*]:0:${#fields[@]}-$lastIdx}))
            [ ${lastIdx} -eq 0 ] && prefix=${COMP_WORDS[$COMP_CWORD]} || prefix=$(tr ' ' '.' <<< $(echo "${fields[@]}."))
            [ "${prefix:0}" == "." ] && prefix=""

            COMPREPLY=( $(compgen -W "$(ls $(tr ' ' '/' <<< $(echo ${fields[@]})))" -- $lastWord ))
            COMPREPLY=(${COMPREPLY[@]/#/$prefix})
            COMPREPLY=(${COMPREPLY[@]/%/.})
            COMPREPLY=(${COMPREPLY[@]/.class./})
            COMPREPLY=(${COMPREPLY[@]/.java./})
            ;;
    esac
    return 0
}

complete -o nospace -o filenames -F _comp_java java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM