Java:Jline3:多个单词自动完成

时间:2018-07-13 01:54:12

标签: java autocomplete jline jline3

我想使用多个单词自动完成,例如:

> we can<TAB>
welcome_trashcan  pecan_seaweed  yeswecan  canwest

因此,所有建议都应同时包含两个关键字。理想情况下,它应该适用于无限的关键字。

我阅读了completion wiki,但是我不知道要遵循的路径。

1 个答案:

答案 0 :(得分:0)

我最终实现了一个新的Interface(以groovy编写):

class MatchAnyCompleter implements Completer {
    protected final List<Candidate> candidateList = []

    MatchAnyCompleter(List<String> list) {
        assert list
        list.each {
            candidateList << new Candidate(AttributedString.stripAnsi(it), it, null, null, null, null, true)
        }
    }

    @Override
    void complete(final LineReader reader, final ParsedLine commandLine, final List<Candidate> selected) {
        assert commandLine != null
        assert selected != null
        selected.addAll(candidateList.findAll {
            Candidate candidate ->
                commandLine.words().stream().allMatch {
                    String keyword ->
                        candidate.value().contains(keyword)
                }
        })
    }
}

测试:

class MatchAnyCompleterTest extends Specification {
    def "Testing matches"() {
        setup:
            def mac = new MatchAnyCompleter([
                    "somevalue",
                    "welcome_trashcan",
                    "pecan_seaweed",
                    "yeswecan",
                    "canwest",
                    "nomatchhere"
            ])
            def cmdLine = new ParsedLine() {
                // non-implemented methods were removed for simplicity
                @Override
                List<String> words() {
                    return ["we","can"]
                }
            }
            List<Candidate> selected = []
            mac.complete(null, cmdLine, selected)
        expect:
            selected.each {
                println it.value()
            }
            assert selected.size() == 4
    }
}

输出:

welcome_trashcan
pecan_seaweed
yeswecan
canwest