Search in sources :

Example 1 with ImmutableStringReader

use of com.mojang.brigadier.ImmutableStringReader in project SpongeCommon by SpongePowered.

the class BrigadierHighlighter method highlight.

@Override
public AttributedString highlight(final LineReader lineReader, final String buffer) {
    final CommandDispatcher<S> dispatcher = this.dispatcherProvider.get();
    if (dispatcher == null) {
        return new AttributedString(buffer);
    }
    try {
        final ParseResults<S> results = dispatcher.parse(buffer, this.commandSourceProvider.get());
        final ImmutableStringReader reader = results.getReader();
        final AttributedStringBuilder builder = new AttributedStringBuilder();
        int lastPos = 0;
        int argColorIdx = 0;
        for (final ParsedCommandNode<S> node : results.getContext().getLastChild().getNodes()) {
            // Sometimes Brigadier will spit out ranges that are invalid for the current input string????
            final int start = Math.min(node.getRange().getStart(), reader.getTotalLength());
            final int end = Math.min(node.getRange().getEnd(), reader.getTotalLength());
            if (lastPos < start) {
                builder.append(reader.getString(), lastPos, start);
            }
            builder.append(reader.getString().substring(start, end), BrigadierHighlighter.ARGUMENT_STYLES[argColorIdx]);
            argColorIdx = (argColorIdx + 1) % BrigadierHighlighter.ARGUMENT_STYLES.length;
            lastPos = end;
        }
        if (lastPos < reader.getTotalLength()) {
            builder.append(reader.getString().substring(lastPos), results.getExceptions().isEmpty() ? BrigadierHighlighter.LITERAL_STYLE : BrigadierHighlighter.ERROR_STYLE);
        }
        return builder.toAttributedString();
    } catch (final Exception ex) {
        SpongeCommon.logger().warn("Error while highlighting console command line", ex);
        return new AttributedString(buffer);
    }
}
Also used : AttributedString(org.jline.utils.AttributedString) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) ImmutableStringReader(com.mojang.brigadier.ImmutableStringReader)

Aggregations

ImmutableStringReader (com.mojang.brigadier.ImmutableStringReader)1 AttributedString (org.jline.utils.AttributedString)1 AttributedStringBuilder (org.jline.utils.AttributedStringBuilder)1