我想知道我如何实现一个ArgumentCompleter,这样如果我完成了一个完整有效的命令,那么它将开始一个新命令的制表符补全。
我会假设它可以像这样构建:
final ConsoleReader consoleReader = new ConsoleReader()
final ArgumentCompleter cyclicalArgument = new ArgumentCompleter();
cyclicalArgument.getCompleters().addAll(Arrays.asList(
new StringsCompleter("foo"),
new StringsCompleter("bar"),
cyclicalArgument));
consoleReader.addCompleter(cyclicalArgument);
consoleReader.readLine();但是,现在,在Tab键完成第一个foo bar后,该命令将停止工作
有没有人足够熟悉这个库,告诉我我将如何实现这个库?或者,有没有一种已知的方法可以做到这一点,但我没有呢?这也是在使用JLine2。
发布于 2016-02-11 02:55:21
这是一项相当艰巨的任务:-)
它由您正在使用的完成器处理。完成器的complete()方法只能用于搜索最后一个空格之后的内容。
例如,如果您查看库的FileNameCompleter:这根本没有完成,所以您将发现没有完成,因为完成器搜索<input1> <input2>,而不仅仅是<input2> :-)
您必须自己实现一个能够找到input2的完成器。
此外,CompletionHandler还必须将您找到的内容附加到您已经键入的内容之后。
下面是更改默认FileNameCompleter的基本实现
protected int matchFiles(final String buffer, final String translated, final File[] files,
final List<CharSequence> candidates) {
// THIS IS NEW
String[] allWords = translated.split(" ");
String lastWord = allWords[allWords.length - 1];
// the lastWord is used when searching the files now
// ---
if (files == null) {
return -1;
}
int matches = 0;
// first pass: just count the matches
for (File file : files) {
if (file.getAbsolutePath().startsWith(lastWord)) {
matches++;
}
}
for (File file : files) {
if (file.getAbsolutePath().startsWith(lastWord)) {
CharSequence name = file.getName() + (matches == 1 && file.isDirectory() ? this.separator() : " ");
candidates.add(this.render(file, name).toString());
}
}
final int index = buffer.lastIndexOf(this.separator());
return index + this.separator().length();
}这里是更改默认CandidateListCompletionHandler的CompletionHandler的complete()-Method
@Override
public boolean complete(final ConsoleReader reader, final List<CharSequence> candidates, final int pos)
throws IOException {
CursorBuffer buf = reader.getCursorBuffer();
// THIS IS NEW
String[] allWords = buf.toString().split(" ");
String firstWords = "";
if (allWords.length > 1) {
for (int i = 0; i < allWords.length - 1; i++) {
firstWords += allWords[i] + " ";
}
}
//-----
// if there is only one completion, then fill in the buffer
if (candidates.size() == 1) {
String value = Ansi.stripAnsi(candidates.get(0).toString());
if (buf.cursor == buf.buffer.length() && this.printSpaceAfterFullCompletion && !value.endsWith(" ")) {
value += " ";
}
// fail if the only candidate is the same as the current buffer
if (value.equals(buf.toString())) {
return false;
}
CandidateListCompletionHandler.setBuffer(reader, firstWords + " " + value, pos);
return true;
} else if (candidates.size() > 1) {
String value = this.getUnambiguousCompletions(candidates);
CandidateListCompletionHandler.setBuffer(reader, value, pos);
}
CandidateListCompletionHandler.printCandidates(reader, candidates);
// redraw the current console buffer
reader.drawLine();
return true;
}https://stackoverflow.com/questions/34996855
复制相似问题