代码之家  ›  专栏  ›  技术社区  ›  lepe

Java:JLILN3:用一个以上的单词自动完成

  •  0
  • lepe  · 技术社区  · 6 年前

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

    > we can<TAB>
    welcome_trashcan  pecan_seaweed  yeswecan  canwest
    

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

    我读了 completion wiki 但我不知道该走哪条路来实现这一目标。

    1 回复  |  直到 6 年前
        1
  •  0
  •   lepe    6 年前

    我最终实现了一个新的接口(它是用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