CompletionMatch completion = shell.complete(prefix.toString());
Completion completions = completion.getValue();
log.log(Level.FINE, "Completions for " + prefix + " are " + completions);
//
Delimiter delimiter = completion.getDelimiter();
try {
// Try to find the greatest prefix among all the results
if (completions.getSize() == 0) {
// Do nothing
} else if (completions.getSize() == 1) {
Map.Entry<String, Boolean> entry = completions.iterator().next();
Appendable buffer = term.getDirectBuffer();
String insert = entry.getKey();
term.getDirectBuffer().append(delimiter.escape(insert));
if (entry.getValue()) {
buffer.append(completion.getDelimiter().getValue());
}
} else {
String commonCompletion = Utils.findLongestCommonPrefix(completions.getValues());
// Format stuff
int width = term.getWidth();
//
String completionPrefix = completions.getPrefix();
// Get the max length
int max = 0;
for (String suffix : completions.getValues()) {
max = Math.max(max, completionPrefix.length() + suffix.length());
}
// Separator : use two whitespace like in BASH
max += 2;
//
StringBuilder sb = new StringBuilder().append('\n');
if (max < width) {
int columns = width / max;
int index = 0;
for (String suffix : completions.getValues()) {
sb.append(completionPrefix).append(suffix);
for (int l = completionPrefix.length() + suffix.length();l < max;l++) {
sb.append(' ');
}
if (++index >= columns) {
index = 0;
sb.append('\n');
}
}
if (index > 0) {
sb.append('\n');
}
} else {
for (Iterator<String> i = completions.getValues().iterator();i.hasNext();) {
String suffix = i.next();
sb.append(commonCompletion).append(suffix);
if (i.hasNext()) {
sb.append('\n');
}
}
sb.append('\n');
}
// We propose
term.append(sb);
// Rewrite prompt
writePromptFlush();
// If we have common completion we append it now
if (commonCompletion.length() > 0) {
term.getDirectBuffer().append(delimiter.escape(commonCompletion));
}
}
}
catch (IOException e) {
log.log(Level.SEVERE, "Could not write completion", e);