многоуровневый анализ jline - PullRequest
1 голос
/ 29 октября 2010

Я пытаюсь заставить JLine выполнить завершение табуляции, чтобы я мог ввести что-то вроде следующего:

commandname --arg1 value1 --arg2 value2

Я использую следующий код:

final List<Completor> completors = Arrays.asList(
    new SimpleCompletor("commandname "),
    new SimpleCompletor("--arg1"),
    new SimpleCompletor("--arg2"),
    new NullCompletor());

consoleReader.addCompletor(new ArgumentCompletor(completors));

Но послевведите вкладку завершения значения value2.

(Дополнительный вопрос, могу ли я проверить значение1 как дату, используя jline?)

Ответы [ 3 ]

3 голосов
/ 25 октября 2011

У меня была та же проблема, и я решил ее, создав свои собственные классы для выполнения команд с помощью jLine. Мне просто нужно было реализовать свой собственный Completor.

Я разрабатываю приложение, которое может помочь администраторам баз данных вводить не только имена команд, но и параметры. Я использую jLine только для взаимодействия с Терминалом и создал еще один Completor.

Я должен предоставить полную грамматику Completor, и это является целью моего приложения. Он называется Zemucan и находится в SourceForge; это приложение изначально ориентировано на DB2, но может быть включена любая грамматика. Пример используемого Completor:

public final int complete(final String buffer, final int cursor,
        @SuppressWarnings("rawtypes") final List candidateRaw) {
final List<String> candidates = candidateRaw;

    final String phrase = buffer.substring(0, cursor);
    try {
        // Analyzes the typed phrase. This is my program: Zemucan.
        // ReturnOptions is an object that contains the possible options of the command.
        // It can propose complete the command name, or propose options.
        final ReturnOptions answer = InterfaceCore.analyzePhrase(phrase);

        // The first candidate is the new phrase.
        final String complete = answer.getPhrase().toLowerCase();

        // Deletes extra spaces.
        final String trim = phrase.trim().toLowerCase();

        // Compares if they are equal.
        if (complete.startsWith(trim)) {
            // Takes the difference.
            String diff = complete.substring(trim.length());
            if (diff.startsWith(" ") && phrase.endsWith(" ")) {
                diff = diff.substring(1, diff.length());
            }
            candidates.add(diff);
        } else {
            candidates.add("");
        }

        // There are options or phrases, then add them as
        // candidates. There is not a predefined phrase.
        candidates.addAll(this.fromArrayToColletion(answer.getPhrases()));
        candidates.addAll(this.fromArrayToColletion(answer.getOptions()));
        // Adds a dummy option, in order to prevent that
        // jLine adds automatically the option as a phrase.
        if ((candidates.size() == 2) && (answer.getOptions().length == 1)
                && (answer.getPhrases().length == 0)) {
            candidates.add("");
        }
    } catch (final AbstractZemucanException e) {
        String cause = "";
        if (e.getCause() != null) {
            cause = e.getCause().toString();
        }
        if (e.getCause() != null) {
            final Throwable ex = e.getCause();
        }
        System.exit(InputReader.ASSISTING_ERROR);
    }

    return cursor;

Это выдержка из приложения. Вы можете сделать простой Completor, и вы должны предоставить массив опций. В конце концов, вы захотите реализовать свой собственный CompletionHandler, чтобы улучшить способ представления опций пользователю.

Полный код доступен здесь .

0 голосов
/ 28 августа 2017

Удалите NullCompletor, и вы получите то, что хотите. NullCompletor гарантирует, что вся ваша команда состоит всего из 3 слов.

0 голосов
/ 22 марта 2015

Создайте 2 завершителя, затем используйте их для завершения произвольных аргументов.Обратите внимание, что не все аргументы должны быть завершены.

List<Completer> completors = new LinkedList<>();

// Completes using the filesystem
completors.add(new FileNameCompleter());

// Completes using random words
completors.add(new StringsCompleter("--arg0", "--arg1", "command"));

// Aggregate the above completors
AggregateCompleter aggComp = new AggregateCompleter(completors);

// Parse the buffer line and complete each token
ArgumentCompleter argComp = new ArgumentCompleter(aggComp);

// Don't require all completors to match
argComp.setStrict(false);

// Add it all together 
conReader.addCompleter(argComp);
...