【问题标题】:Java console autocompletion with JLine使用 JLine 的 Java 控制台自动完成
【发布时间】:2015-01-30 00:13:18
【问题描述】:

我尝试编写一个带有自动完成功能的简单 Shell。我使用JLine 库。这是我的代码。

public class ConsoleDemo {
    public static void main(String[] args) {
        try {
            ConsoleReader console = new ConsoleReader();
            console.setPrompt(">>> ");
            console.addCompleter(new MyStringsCompleter("a", "aaa", "b", "bbb"));           
            String line;
            while ((line = console.readLine()) != null) {
                console.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

问题是当我按下tab 时,我的应用程序没有完成任何操作。

>>> a [press tab]

如何正确使用它来自动完成我的输入?

UPD

public class MyStringsCompleter implements Completer {

    private final SortedSet<String> strings = new TreeSet<>();

    public MyStringsCompleter(Collection<String> strings) {
        this.strings.addAll(strings);
    }

    public MyStringsCompleter(String... strings) {
        this(asList(strings));
    }

    @Override
    public int complete(String buffer, int cursor, List<CharSequence> candidates) {
        if (buffer == null) {
            candidates.addAll(strings);
        } else {
            for (String match : strings.tailSet(buffer)) {
                if (!match.startsWith(buffer)) {
                    break;
                }
                candidates.add(match);
            }
        }
        if (candidates.size() == 1) {
            candidates.set(0, candidates.get(0) + " ");
        }
        return candidates.isEmpty() ? -1 : 0;
    }
}

【问题讨论】:

    标签: java autocomplete jline


    【解决方案1】:

    问题出在我的 IDE 中。当我不通过 IDE 启动我的应用程序时,一切正常。所以问题出在 IDE 中,它以某种方式拦截了控制台输入。

    【讨论】:

      【解决方案2】:

      StringsCompleter 中简单地添加字符串不会达到您想要的效果。您必须使用来自StringsCompletercomplete 方法。一个例子可以在 here 找到。

      【讨论】:

      • 它没有帮助。我实现了自己的 Completer。
      猜你喜欢
      • 2016-12-20
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 2017-12-31
      • 2017-04-14
      相关资源
      最近更新 更多