Search code examples
javaautocompletejline

Java console autocompletion with JLine


I try to write a simple Shell with autocompletion. I use JLine library. Here is my code.

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();
        }
    }
}

The problem is that my app doesn't complete nothing when I press tab.

>>> a [press tab]

How can I use it right to get autocompletion my input?

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;
    }
}

Solution

  • The problem is in my IDE. When I start my application not through IDE, than all works fine. So the problem is in IDE which somehow intercepts console input.