com.mojang.brigadier.suggestion.SuggestionsBuilder Java Examples

The following examples show how to use com.mojang.brigadier.suggestion.SuggestionsBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FabricClientSparkPlugin.java    From spark with GNU General Public License v3.0 6 votes vote down vote up
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSource> context, SuggestionsBuilder builder) throws CommandSyntaxException {
    String[] split = context.getInput().split(" ");
    if (split.length == 0 || (!split[0].equals("/sparkc") && !split[0].equals("/sparkclient"))) {
        return Suggestions.empty();
    }

    String[] args = Arrays.copyOfRange(split, 1, split.length);

    return CompletableFuture.supplyAsync(() -> {
        for (String suggestion : this.platform.tabCompleteCommand(new FabricCommandSender(this.minecraft.player, this), args)) {
            builder.suggest(suggestion);
        }
        return builder.build();
    });
}
 
Example #2
Source File: PointType.java    From Chimera with MIT License 6 votes vote down vote up
@Override
public void suggest(SuggestionsBuilder builder, String[] parts) {
    if (builder.getRemaining().isBlank()) {
        builder.suggest("~").suggest("~ ~").suggest("~ ~ ~");
        return;
    }
    
    var prefix = builder.getRemaining().charAt(0) == '^' ? '^' : '~';
    if (parts.length == 1) {
        builder.suggest(parts[0] + " " + prefix)
               .suggest(parts[0] + " " + prefix + " " + prefix);
        
    } else if (parts.length == 2) {
        builder.suggest(parts[0] + " " + parts[1] + " " + prefix);
    }
}
 
Example #3
Source File: ForgeClientSparkPlugin.java    From spark with GNU General Public License v3.0 6 votes vote down vote up
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<ISuggestionProvider> context, SuggestionsBuilder builder) throws CommandSyntaxException {
    String chat = context.getInput();
    String[] split = chat.split(" ");
    if (split.length == 0 || (!split[0].equals("/sparkc") && !split[0].equals("/sparkclient"))) {
        return Suggestions.empty();
    }

    String[] args = Arrays.copyOfRange(split, 1, split.length);

    return CompletableFuture.supplyAsync(() -> {
        for (String suggestion : this.platform.tabCompleteCommand(new ForgeCommandSender(this.minecraft.player, this), args)) {
            builder.suggest(suggestion);
        }
        return builder.build();
    });
}
 
Example #4
Source File: ScriptCommand.java    From fabric-carpet with MIT License 6 votes vote down vote up
private static CompletableFuture<Suggestions> suggestCode(
        CommandContext<ServerCommandSource> context,
        SuggestionsBuilder suggestionsBuilder
)
{
    CarpetScriptHost currentHost = getHost(context);
    String previous = suggestionsBuilder.getRemaining().toLowerCase(Locale.ROOT);
    int strlen = previous.length();
    StringBuilder lastToken = new StringBuilder();
    for (int idx = strlen-1; idx >=0; idx--)
    {
        char ch = previous.charAt(idx);
        if (Character.isLetterOrDigit(ch) || ch == '_') lastToken.append(ch); else break;
    }
    if (lastToken.length() == 0)
        return suggestionsBuilder.buildFuture();
    String prefix = lastToken.reverse().toString();
    String previousString =  previous.substring(0,previous.length()-prefix.length()) ;
    suggestFunctions(currentHost, previousString, prefix).forEach(text -> suggestionsBuilder.suggest(previousString+text));
    return suggestionsBuilder.buildFuture();
}
 
Example #5
Source File: EntityArgumentType_1_12_2.java    From multiconnect with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
    if (!(context.getSource() instanceof CommandSource))
        return builder.buildFuture();

    StringReader reader = new StringReader(builder.getInput());
    reader.setCursor(builder.getStart());

    CompletableFuture<Suggestions> playerCompletions;
    if ((reader.canRead() && reader.peek() == '@') || !suggestPlayerNames) {
        playerCompletions = Suggestions.empty();
    } else {
        playerCompletions = ((CommandSource) context.getSource()).getCompletions((CommandContext<CommandSource>) context, builder.restart());
    }

    EntitySelectorParser parser = new EntitySelectorParser(reader, singleTarget, playersOnly);
    try {
        parser.parse();
    } catch (CommandSyntaxException ignore) {
    }
    CompletableFuture<Suggestions> selectorCompletions = parser.suggestor.apply(builder.restart());

    return CompletableFuture.allOf(playerCompletions, selectorCompletions)
            .thenCompose(v -> UnionArgumentType.mergeSuggestions(playerCompletions.join(), selectorCompletions.join()));
}
 
Example #6
Source File: VRCommandHandler.java    From ViaFabric with MIT License 6 votes vote down vote up
public CompletableFuture<Suggestions> suggestion(CommandContext<? extends CommandSource> ctx, SuggestionsBuilder builder) {
    String[] args;
    try {
        args = StringArgumentType.getString(ctx, "args").split(" ", -1);
    } catch (IllegalArgumentException ignored) {
        args = new String[]{""};
    }
    String[] pref = args.clone();
    pref[pref.length - 1] = "";
    String prefix = String.join(" ", pref);
    onTabComplete(new NMSCommandSender(ctx.getSource()), args)
            .stream()
            .map(it -> {
                SuggestionsBuilder b = new SuggestionsBuilder(builder.getInput(), prefix.length() + builder.getStart());
                b.suggest(it);
                return b;
            })
            .forEach(builder::add);
    return builder.buildFuture();
}
 
Example #7
Source File: EnchantmentTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
@Test
void listSuggestions() {
    EnchantmentType.ENCHANTMENTS.put("arrow_damage", mock(Enchantment.class));
    EnchantmentType.ENCHANTMENTS.put("arrow_fire", mock(Enchantment.class));
    
    SuggestionsBuilder builder = when(mock(SuggestionsBuilder.class).getRemaining()).thenReturn("arro").getMock();
    type.listSuggestions(null, builder);
    
    verify(builder).suggest("arrow_damage");
    verify(builder).suggest("arrow_fire");
}
 
Example #8
Source File: CommandAPIHandler.java    From 1.13-Command-API with Apache License 2.0 5 votes vote down vote up
private <T> RequiredArgumentBuilder<?, T> getRequiredArgumentBuilderDynamic(String argumentName, Argument type,
		CommandPermission permission) {
	if(type.getOverriddenSuggestions() == null) {
		return RequiredArgumentBuilder.argument(argumentName, (ArgumentType<T>) type.getRawType()).requires(clw -> 
             permissionCheck(nms.getCommandSenderForCLW(clw), permission)
        );
	} else {
		return getRequiredArgumentBuilderWithProvider(argumentName, type.getRawType(), permission,
				(CommandContext context, SuggestionsBuilder builder) -> getSuggestionsBuilder(builder,
						type.getOverriddenSuggestions().apply(nms.getCommandSenderForCLW(context.getSource()))));
	}
}
 
Example #9
Source File: PointType.java    From Chimera with MIT License 5 votes vote down vote up
@Override
public void suggest(SuggestionsBuilder builder, String[] parts) {
    if (builder.getRemaining().isBlank()) {
        builder.suggest("~").suggest("~ ~");
        
    } else if (parts.length == 1) {
        var prefix = builder.getRemaining().charAt(0) == '^' ? '^' : '~';
        builder.suggest(parts[0] + " " + prefix);
    }
}
 
Example #10
Source File: CartesianTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
@Test
void listSuggestions_location() {
    var builder = mock(SuggestionsBuilder.class);
    var location = mock(Location.class);
    
    type.suggest(builder, new String[0], location);
    
    verifyNoInteractions(builder);
    verifyNoInteractions(location);
}
 
Example #11
Source File: ParticleTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
@Test
void listSuggestions() {
    SuggestionsBuilder builder = when(mock(SuggestionsBuilder.class).getRemaining()).thenReturn("block").getMock();
    type.listSuggestions(null, builder);
    
    verify(builder).suggest("block_crack");
    verify(builder).suggest("block_dust");
}
 
Example #12
Source File: ClientSuggestionProviderTest.java    From Chimera with MIT License 5 votes vote down vote up
@Test
void getSuggestions() {
    SuggestionsBuilder builder = mock(SuggestionsBuilder.class);
    
    ClientSuggestionProvider.ENTITIES.getSuggestions(null, builder);
    
    verify(builder).buildFuture();
    verifyNoMoreInteractions(builder);
}
 
Example #13
Source File: WorldTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
@Test
void listSuggestions() {
    SuggestionsBuilder builder = when(mock(SuggestionsBuilder.class).getRemaining()).thenReturn("worl").getMock();
    
    type.listSuggestions(null, builder);
    
    verify(builder).suggest("\"world name\"");
    verify(builder).suggest("world_name");
}
 
Example #14
Source File: PlayerTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("listSuggestions_parameters")
void listSuggestions(CommandSender source, String remaining, boolean see, int times) {
    CommandContext<CommandSender> context = when(mock(CommandContext.class).getSource()).thenReturn(source).getMock();
    SuggestionsBuilder builder = when(mock(SuggestionsBuilder.class).getRemaining()).thenReturn(remaining).getMock();
    
    when(player.canSee(any())).thenReturn(see);
    
    type.listSuggestions(context, builder);
    
    verify(builder, times(times)).suggest("Pante");
}
 
Example #15
Source File: PointTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("suggest_parameters")
void suggest(String[] parts, SuggestionsBuilder expected) {
    var suggestions = new SuggestionsBuilder(expected.getInput(), 0);
    type.suggest(suggestions, parts);
    
    assertEquals(expected.build(), suggestions.build());
}
 
Example #16
Source File: PointTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
static Stream<Arguments> suggest_parameters() {
    return Stream.of(
        of(new String[] {}, new SuggestionsBuilder("", 0).suggest("~").suggest("~ ~")),
        of(new String[] {}, new SuggestionsBuilder(" ", 0).suggest("~").suggest("~ ~")),
        of(new String[] {}, new SuggestionsBuilder("  ", 0).suggest("~").suggest("~ ~")),
        of(new String[] {"^1"}, new SuggestionsBuilder("^1", 0).suggest("^1 ^")),
        of(new String[] {"~1"}, new SuggestionsBuilder("~1", 0).suggest("~1 ~"))
    );
}
 
Example #17
Source File: PointTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("suggest_parameters")
void suggest(String[] parts, SuggestionsBuilder expected) {
    var suggestions = new SuggestionsBuilder(expected.getInput(), 0);
    type.suggest(suggestions, parts);
    
    assertEquals(expected.build(), suggestions.build());
}
 
Example #18
Source File: PointTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
static Stream<Arguments> suggest_parameters() {
    return Stream.of(
        of(new String[] {}, new SuggestionsBuilder("", 0).suggest("~").suggest("~ ~").suggest("~ ~ ~")),
        of(new String[] {}, new SuggestionsBuilder(" ", 0).suggest("~").suggest("~ ~").suggest("~ ~ ~")),
        of(new String[] {}, new SuggestionsBuilder("  ", 0).suggest("~").suggest("~ ~").suggest("~ ~ ~")),
        of(new String[] {"^1"}, new SuggestionsBuilder("^1", 0).suggest("^1 ^").suggest("^1 ^ ^")),
        of(new String[] {"~1"}, new SuggestionsBuilder("~1", 0).suggest("~1 ~").suggest("~1 ~ ~")),
        of(new String[] {"~1", "2"}, new SuggestionsBuilder("~1 2", 0).suggest("~1 2 ~"))
    );
}
 
Example #19
Source File: PlayersTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("listSuggestions_parameters")
void listSuggestions(CommandSender source, boolean see, SuggestionsBuilder expected) throws InterruptedException, ExecutionException {
    CommandContext<CommandSender> context = when(mock(CommandContext.class).getSource()).thenReturn(source).getMock();
    when(player.canSee(any())).thenReturn(see);
    
    var future = type.listSuggestions(context, new SuggestionsBuilder(expected.getInput(), 0));
    
    assertEquals(expected.build(), future.get());
}
 
Example #20
Source File: PlayersTypeTest.java    From Chimera with MIT License 5 votes vote down vote up
static Stream<Arguments> listSuggestions_parameters() {
    return Stream.of(
        of(player, true, new SuggestionsBuilder("P", 0).suggest("Pante")),
        of(sender, true, new SuggestionsBuilder("P", 0).suggest("Pante")),
        of(player, true, new SuggestionsBuilder("Invalid", 0)),
        of(player, false, new SuggestionsBuilder("P", 0)),
        
        of(player, true, new SuggestionsBuilder("@", 0).suggest("@a", PlayersType.ALL).suggest("@r", PlayersType.RANDOM)),
        of(player, true, new SuggestionsBuilder("\"", 0).suggest("\"Pante\"").suggest("\"@r\"", PlayersType.RANDOM)),
        of(player, true, new SuggestionsBuilder("\"Bob, P", 0).suggest("\"Bob, Pante\"")),
        of(player, true, new SuggestionsBuilder("\"Bob, P\"", 0).suggest("\"Bob, Pante\""))
    );
}
 
Example #21
Source File: CommandAPIHandler.java    From 1.13-Command-API with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<Suggestions> getSuggestionsBuilder(SuggestionsBuilder builder, String[] array) {
	String remaining = builder.getRemaining().toLowerCase(Locale.ROOT);
	for (int i = 0; i < array.length; i++) {
		String str = array[i];
		if (str.toLowerCase(Locale.ROOT).startsWith(remaining)) {
			builder.suggest(str);
		}
	}
	return builder.buildFuture();
}
 
Example #22
Source File: FabricServerSparkPlugin.java    From spark with GNU General Public License v3.0 5 votes vote down vote up
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<ServerCommandSource> context, SuggestionsBuilder builder) throws CommandSyntaxException {
    String[] args = processArgs(context);
    if (args == null) {
        return Suggestions.empty();
    }
    ServerPlayerEntity player = context.getSource().getPlayer();

    return CompletableFuture.supplyAsync(() -> {
        for (String suggestion : this.platform.tabCompleteCommand(new FabricCommandSender(player, this), args)) {
            builder.suggest(suggestion);
        }
        return builder.build();
    });
}
 
Example #23
Source File: ForgeServerSparkPlugin.java    From spark with GNU General Public License v3.0 5 votes vote down vote up
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSource> context, SuggestionsBuilder builder) throws CommandSyntaxException {
    String[] args = processArgs(context);
    if (args == null) {
        return Suggestions.empty();
    }

    ServerPlayerEntity player = context.getSource().asPlayer();
    return CompletableFuture.supplyAsync(() -> {
        for (String suggestion : this.platform.tabCompleteCommand(new ForgeCommandSender(player, this), args)) {
            builder.suggest(suggestion);
        }
        return builder.build();
    });
}
 
Example #24
Source File: BlockStateArgumentType_1_12_2.java    From multiconnect with MIT License 5 votes vote down vote up
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
    int spaceIndex = builder.getRemaining().indexOf(' ');
    if (spaceIndex == -1) {
        CommandSource.suggestIdentifiers(Registry.BLOCK.getIds().stream().filter(id -> isValidBlock(Registry.BLOCK.get(id))), builder);
        return builder.buildFuture();
    }

    Identifier blockId = Identifier.tryParse(builder.getInput().substring(builder.getStart(), builder.getStart() + spaceIndex));

    String propertiesStr = builder.getInput().substring(builder.getStart() + spaceIndex + 1);

    int commaIndex = propertiesStr.lastIndexOf(',');
    int equalsIndex = propertiesStr.lastIndexOf('=');
    builder = builder.createOffset(builder.getStart() + spaceIndex + commaIndex + 2);

    if (commaIndex == -1 && equalsIndex == -1) {
        CommandSource.suggestMatching(new String[] {"default"}, builder);
        if (test)
            CommandSource.suggestMatching(new String[] {"*"}, builder);
    }

    if (blockId == null || !BlockStateReverseFlattening.OLD_PROPERTIES.containsKey(blockId))
        return builder.buildFuture();

    if (equalsIndex <= commaIndex) {
        CommandSource.suggestMatching(BlockStateReverseFlattening.OLD_PROPERTIES.get(blockId).stream().map(str -> str + "="), builder);
    } else {
        String property = builder.getInput().substring(builder.getStart(), builder.getStart() + equalsIndex - commaIndex - 1);
        List<String> values = BlockStateReverseFlattening.OLD_PROPERTY_VALUES.get(Pair.of(blockId, property));
        builder = builder.createOffset(builder.getStart() + equalsIndex - commaIndex);
        CommandSource.suggestMatching(values, builder);
    }

    return builder.buildFuture();
}
 
Example #25
Source File: CommandArgumentType.java    From multiconnect with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
    CommandDispatcher<S> dispatcher = ((CommandDispatcher<S>) this.dispatcher);
    StringReader reader = new StringReader(builder.getInput());
    reader.setCursor(builder.getStart());
    ParseResults<S> results = dispatcher.parse(reader, context.getSource());
    return dispatcher.getCompletionSuggestions(results);
}
 
Example #26
Source File: EntityArgumentType_1_12_2.java    From multiconnect with MIT License 5 votes vote down vote up
private void suggestOption() {
    int start = reader.getCursor();
    List<String> seenOptionsCopy = new ArrayList<>(seenOptions);

    suggestor = builder -> {
        SuggestionsBuilder normalOptionBuilder = builder.createOffset(start);
        CommandSource.suggestMatching(SELECTOR_OPTIONS.keySet().stream()
                .filter(opt -> SELECTOR_OPTIONS.get(opt).isAllowed(this))
                .filter(opt -> !seenOptionsCopy.contains(opt))
                .map(opt -> opt + "=")
                .collect(Collectors.toSet()), normalOptionBuilder);
        CompletableFuture<Suggestions> normalOptions = normalOptionBuilder.buildFuture();

        SuggestionsBuilder scoreOptionBuilder = builder.createOffset(start);
        CompletableFuture<Suggestions> scoreOptions = getScoreObjectives().thenCompose(objectives -> {
            CommandSource.suggestMatching(objectives.stream()
                    .map(str -> "score_" + str)
                    .filter(str -> !seenOptionsCopy.contains(str))
                    .map(str -> str + "="),
                    scoreOptionBuilder);
            CommandSource.suggestMatching(objectives.stream()
                    .map(str -> "score_" + str + "_min")
                    .filter(str -> !seenOptionsCopy.contains(str))
                    .map(str -> str + "="),
                    scoreOptionBuilder);
            return scoreOptionBuilder.buildFuture();
        });

        return CompletableFuture.allOf(normalOptions, scoreOptions)
                .thenCompose(v -> UnionArgumentType.mergeSuggestions(normalOptions.join(), scoreOptions.join()));
    };
}
 
Example #27
Source File: LiteralCommandNode.java    From brigadier with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) {
    if (literal.toLowerCase().startsWith(builder.getRemaining().toLowerCase())) {
        return builder.suggest(literal).buildFuture();
    } else {
        return Suggestions.empty();
    }
}
 
Example #28
Source File: ArgumentCommandNode.java    From brigadier with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) throws CommandSyntaxException {
    if (customSuggestions == null) {
        return type.listSuggestions(context, builder);
    } else {
        return customSuggestions.getSuggestions(context, builder);
    }
}
 
Example #29
Source File: BoolArgumentType.java    From brigadier with MIT License 5 votes vote down vote up
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) {
    if ("true".startsWith(builder.getRemaining().toLowerCase())) {
        builder.suggest("true");
    }
    if ("false".startsWith(builder.getRemaining().toLowerCase())) {
        builder.suggest("false");
    }
    return builder.buildFuture();
}
 
Example #30
Source File: UnionArgumentType.java    From multiconnect with MIT License 5 votes vote down vote up
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
    CompletableFuture<Suggestions> leftFuture = left.listSuggestions(context, builder.restart());
    CompletableFuture<Suggestions> rightFuture = right.listSuggestions(context, builder.restart());
    return CompletableFuture.allOf(leftFuture, rightFuture)
            .thenCompose(v -> mergeSuggestions(leftFuture.join(), rightFuture.join()));
}