### Register Commands with Bukkit API Source: https://context7.com/typst-io/command/llms.txt Integrates custom commands into the Bukkit/Spigot plugin system. This example demonstrates defining a 'game' command with 'start' and 'stop' subcommands, handling their execution, and registering them using BukkitCommands.register. It requires the typst-command library and Bukkit API. ```java import io.typst.command.Command; import io.typst.command.bukkit.BukkitCommands; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; import static io.typst.command.Command.pair; import static io.typst.command.StandardArguments.*; public class MyPlugin extends JavaPlugin { interface GameCommand { record Start(String mapName) implements GameCommand {} record Stop() implements GameCommand {} } @Override public void onEnable() { // Define command structure Command gameCmd = Command.mapping( pair("start", Command.argument(GameCommand.Start::new, strArg)), pair("stop", Command.present(new GameCommand.Stop())) ); // Register with executor BukkitCommands.register( "game", gameCmd, this::executeGameCommand, this ); } private void executeGameCommand(CommandSender sender, GameCommand cmd) { if (cmd instanceof GameCommand.Start start) { sender.sendMessage("Starting game on map: " + start.mapName()); // Start game logic here } else if (cmd instanceof GameCommand.Stop) { sender.sendMessage("Stopping game"); // Stop game logic here } } } ``` -------------------------------- ### Java Contextual Tab Completion Example Source: https://context7.com/typst-io/command/llms.txt Demonstrates creating a context-aware tab completer in Java. It defines completers that provide different suggestions based on the `ParseContext`'s sender ID. This example shows how to integrate these completers into command arguments and perform tab completion for different user types. ```java import io.typst.command.Argument; import io.typst.command.ParseContext; import io.typst.command.CommandSource; import java.util.List; import java.util.function.Function; // Create contextual tab completer Function> contextualCompleter = ctx -> { String senderId = ctx.getSource().getId(); List args = ctx.getArgs(); // Return different suggestions based on context if (senderId.equals("admin")) { return List.of("creative", "survival", "spectator", "adventure"); } else { return List.of("survival", "adventure"); } }; // Create argument with contextual completer Argument contextualArg = Argument.ofContext( "mode", String.class, args -> { String arg = args.isEmpty() ? "" : args.get(0); return new io.typst.command.algebra.Tuple2<>( java.util.Optional.of(arg), args.isEmpty() ? args : args.subList(1, args.size()) ); }, contextualCompleter ); // Use in command record ChangeMode(String mode) {} Command.Parser cmd = Command.argument(ChangeMode::new, contextualArg); // Tab complete with context CommandSource adminSource = new CommandSource("admin"); CommandTabResult adminTabs = Command.tabComplete( adminSource, new String[]{ "" }, cmd ); // Returns: ["creative", "survival", "spectator", "adventure"] CommandSource userSource = new CommandSource("user123"); CommandTabResult userTabs = Command.tabComplete( userSource, new String[]{ "" }, cmd ); // Returns: ["survival", "adventure"] ``` -------------------------------- ### Java Command Parsing and Execution Source: https://github.com/typst-io/command/blob/main/README.md This Java example illustrates how to define and parse commands using the Typst IO Command library. It shows creating a command mapping, parsing arguments, and executing the parsed command logic with type checking. ```java // core/src/test/../CommandTest.java // MyCommand = AddItem | RemoveItem | OpenItemList | ReloadCommand Command command = Command.mapping( pair("item", Command.mapping( pair("open", Command.present(new OpenItemList())), // intArg: Argument // strArg: Argument // AddItem::new = (Integer, String) -> AddItem pair("add", Command.argument(AddItem::new, intArg, strArg)), pair("remove", Command.argument(RemoveItem::new, intArg)) )), pair("reload", Command.present(new ReloadCommand())) ); // parsing String[] args = new String[] {"item", "add", "0", "NAME"}; MyCommand algebra = Command.parseO(args, command).orElse(null); // execution, check with if-instanceof. // assumes `MyCommand` is sealed, treat like Enum. // therefore, this is a valid type casting (not unsafe). if (algebra instanceof MyCommand.AddItem) { MyCommand.AddItem addItem = (MyCommand.AddItem) algebra; println(String.format("Adding item %s, %s!", addItem.getIndex(), addItem.getName())); } else if (algebra instanceof MyCommand.RemoveItem) { MyCommand.RemoveItem removeItem = (MyCommand.RemoveItem) algebra; println(String.format("Removing item %s", removeItem.getIndex())); } ``` -------------------------------- ### Use Bukkit-Specific Arguments in Commands Source: https://context7.com/typst-io/command/llms.txt Utilizes Bukkit-specific argument types within the typst-command framework for enhanced command creation. This example shows how to define 'enchant' and 'give' commands that accept Bukkit entity types like Player, Material, and Enchantment, enabling auto-completion and validation. Dependencies include typst-command and Bukkit API. ```java import io.typst.command.Command; import io.typst.command.bukkit.BukkitArguments; import io.typst.command.bukkit.BukkitCommands; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; import static io.typst.command.Command.pair; import static io.typst.command.StandardArguments.*; record EnchantItem(Player player, Enchantment enchant, int level) {} record GiveMaterial(Player player, Material material, int amount) {} interface AdminCommand { record Enchant(Player player, Enchantment enchant, int level) implements AdminCommand {} record Give(Player player, Material material, int amount) implements AdminCommand {} } public class AdminPlugin extends JavaPlugin { @Override public void onEnable() { Command adminCmd = Command.mapping( pair("enchant", Command.argument( AdminCommand.Enchant::new, BukkitArguments.playerArg, // Auto-completes online players BukkitArguments.enchantArg, // Auto-completes enchantments intArg )), pair("give", Command.argument( AdminCommand.Give::new, BukkitArguments.playerArg, // Validates player exists BukkitArguments.materialArg, // Auto-completes all materials intArg )) ); BukkitCommands.register("admin", adminCmd, this::execute, this); } private void execute(CommandSender sender, AdminCommand cmd) { if (cmd instanceof AdminCommand.Enchant e) { e.player().getInventory().getItemInMainHand() .addEnchantment(e.enchant(), e.level()); sender.sendMessage("Enchanted " + e.player().getName() + "'s item"); } else if (cmd instanceof AdminCommand.Give g) { g.player().getInventory().addItem( new org.bukkit.inventory.ItemStack(g.material(), g.amount()) ); } } } ``` -------------------------------- ### Define Shop Commands with Kotlin DSL Source: https://context7.com/typst-io/command/llms.txt Demonstrates defining a sealed interface for shop commands (Buy, Sell, List) and registering them with Bukkit using a Kotlin DSL. It utilizes extension functions for concise command mapping and argument definition. Commands are executed based on the sender and parsed command. ```kotlin import io.typst.command.kotlin.* import io.typst.command.StandardArguments.* import org.bukkit.plugin.java.JavaPlugin sealed interface ShopCommand { data class Buy(val item: String, val quantity: Int) : ShopCommand data class Sell(val item: String, val quantity: Int) : ShopCommand data object List : ShopCommand } class ShopPlugin : JavaPlugin() { override fun onEnable() { // Define commands using Kotlin DSL val shopCmd = commandMap( "buy" to command(::Buy, strArg, intArg), "sell" to command(::Sell, strArg, intArg), "list" to command(ShopCommand.List) ) // Register with Bukkit (using Java interop) io.typst.command.bukkit.BukkitCommands.register( "shop", shopCmd, { sender, cmd -> executeShop(sender, cmd) }, this ) } private fun executeShop(sender: org.bukkit.command.CommandSender, cmd: ShopCommand) { when (cmd) { is ShopCommand.Buy -> sender.sendMessage("Buying ${cmd.quantity}x ${cmd.item}") is ShopCommand.Sell -> sender.sendMessage("Selling ${cmd.quantity}x ${cmd.item}") is ShopCommand.List -> sender.sendMessage("Available items: Diamond, Gold, Iron") } } } // Example with fallback command val cmdWithFallback = commandMap( fallback = command { ShopCommand.List }, "buy" to command(ShopCommand::Buy, strArg, intArg), "sell" to command(ShopCommand::Sell, strArg, intArg) ) ``` -------------------------------- ### Define and Parse Commands with Subcommands (Java) Source: https://context7.com/typst-io/command/llms.txt Demonstrates defining command structures with subcommands using `Command.mapping`. It shows how to parse arguments and handle success or failure results, extracting the specific command executed. ```java import io.typst.command.Command; import static io.typst.command.Command.pair; import static io.typst.command.StandardArguments.*; // Define command result types as sealed interface public interface ItemCommand { record Add(int index, String name) implements ItemCommand {} record Remove(int index) implements ItemCommand {} record Open() implements ItemCommand {} } // Define command structure with subcommands Command itemCmd = Command.mapping( pair("add", Command.argument(ItemCommand.Add::new, intArg, strArg)), pair("remove", Command.argument(ItemCommand.Remove::new, intArg)), pair("open", Command.present(new ItemCommand.Open())) ); // Parse command arguments String[] args = new String[]{"add", "5", "Diamond"}; Either, CommandSuccess> result = Command.parse(args, itemCmd); // Handle result if (result instanceof Either.Right) { CommandSuccess success = ((Either.Right>) result).getRight(); ItemCommand cmd = success.getCommand(); if (cmd instanceof ItemCommand.Add add) { System.out.println("Adding item: " + add.name() + " at index " + add.index()); } } ``` -------------------------------- ### Add Descriptions and Permissions to Java Commands Source: https://context7.com/typst-io/command/llms.txt Shows how to add descriptions and permissions to commands defined in Java using the Typst command API. This metadata is used for generating help messages and validating user permissions. It demonstrates extracting command specifications for usage and permission display. ```java import io.typst.command.Command; import io.typst.command.CommandSpec; import static io.typst.command.Command.pair; import static io.typst.command.StandardArguments.*; interface ModCommand { record Ban(String player, String reason) implements ModCommand {} record Unban(String player) implements ModCommand {} } Command modCmd = Command.mapping( pair("ban", Command.argument(ModCommand.Ban::new, strArg, strArg) .withDescription("Ban a player from the server") .withPermission("mod.ban")), pair("unban", Command.argument(ModCommand.Unban::new, strArg) .withDescription("Unban a player") .withPermission("mod.unban")) ); // Extract command specifications for help generation for (Map.Entry, Command> entry : Command.getEntries(modCmd)) { CommandSpec spec = CommandSpec.from(entry.getValue()); String usage = "/" + String.join(" ", entry.getKey()); String desc = spec.getDescription(); String perm = spec.getPermission(); System.out.println(usage + (desc.isEmpty() ? "" : " - " + desc)); if (!perm.isEmpty()) { System.out.println(" Permission: " + perm); } } // Output: // /ban - Ban a player from the server // Permission: mod.ban // /unban - Unban a player // Permission: mod.unban ``` -------------------------------- ### Import Command Library with Gradle Source: https://github.com/typst-io/command/blob/main/README.md This snippet shows how to add the Typst IO Command library to your project using Gradle. It specifies the Maven Central repository and the `command-bukkit` dependency with a specific version. ```groovy repositories { mavenCentral() } dependencies { implementation 'io.typst:command-bukkit:3.1.6' } ``` -------------------------------- ### Implement Optional Command Arguments in Java Source: https://context7.com/typst-io/command/llms.txt Explains how to support optional command arguments and provide fallback values using the Typst Command API in Java. It demonstrates creating an optional argument, defining a command that accepts it, and parsing commands with and without the optional argument present. ```java import io.typst.command.Argument; import io.typst.command.Command; import static io.typst.command.StandardArguments.*; import java.util.Optional; // Create optional argument Argument> optionalIntArg = intArg.asOptional(); record SetSpeed(String player, Optional speed) {} Command.Parser speedCmd = Command.argument( SetSpeed::new, strArg, optionalIntArg ); // Parse with argument present Either> result1 = Command.parse(new String[]{"Steve", "10"}, speedCmd); // speed = Optional.of(10) // Parse without optional argument Either> result2 = Command.parse(new String[]{"Steve"}, speedCmd); // speed = Optional.empty() // Use fallback value if (result2 instanceof Either.Right) { SetSpeed cmd = ((Either.Right>) result2) .getRight().getCommand(); int speed = cmd.speed().orElse(5); // Default to 5 System.out.println("Setting speed for " + cmd.player() + " to " + speed); } ``` -------------------------------- ### Custom Argument Types and Tab Completion (Java) Source: https://context7.com/typst-io/command/llms.txt Shows how to create custom argument parsers, including defining tab completion suggestions. This allows for flexible input handling and enhanced user experience in command-line interfaces. ```java import io.typst.command.Argument; import io.typst.command.Command; import java.util.Arrays; import java.util.List; import java.util.Optional; // Define custom enum enum GameMode { SURVIVAL, CREATIVE, ADVENTURE, SPECTATOR } // Create custom argument with parser and tab completer Argument gameModeArg = Argument.ofUnary( "gamemode", GameMode.class, s -> { try { return Optional.of(GameMode.valueOf(s.toUpperCase())); } catch (IllegalArgumentException e) { return Optional.empty(); } }, () -> Arrays.asList("survival", "creative", "adventure", "spectator") ); // Use in command record SetGameMode(String player, GameMode mode) {} Command.Parser cmd = Command.argument( SetGameMode::new, StandardArguments.strArg, gameModeArg ); // Parse with validation Either, CommandSuccess> result = Command.parse(new String[]{"Alex", "creative"}, cmd); // Tab completion CommandTabResult tabs = Command.tabComplete( new String[]{"Alex", "cre"}, cmd ); // Returns: ["creative"] ``` -------------------------------- ### Parse Commands with Typed Arguments (Java) Source: https://context7.com/typst-io/command/llms.txt Illustrates defining commands with multiple typed arguments using `Command.argument`. This allows for automatic parsing and validation of input strings into strongly-typed objects. ```java import io.typst.command.Command; import io.typst.command.Argument; import static io.typst.command.StandardArguments.*; // Define command result type record TeleportCommand(String playerName, int x, int y, int z) {} // Create command with multiple typed arguments Command.Parser teleportCmd = Command.argument( TeleportCommand::new, strArg, // playerName: String intArg, // x: int intArg, // y: int intArg // z: int ); // Parse command String[] args = new String[]{"Steve", "100", "64", "-200"}; Either, CommandSuccess> result = Command.parse(args, teleportCmd); // Extract parsed result if (result instanceof Either.Right) { TeleportCommand cmd = ((Either.Right>) result) .getRight() .getCommand(); System.out.println("Teleporting " + cmd.playerName() + " to (" + cmd.x() + ", " + cmd.y() + ", " + cmd.z() + ")"); } // Output: Teleporting Steve to (100, 64, -200) ``` -------------------------------- ### Define Nested Command Hierarchies in Java Source: https://context7.com/typst-io/command/llms.txt Demonstrates how to build multi-level command structures with subcommand trees using the Typst Command API in Java. It defines interfaces for server and player commands, builds a nested command structure using mappings and pairs, and parses a command with arguments. ```java import io.typst.command.Command; import static io.typst.command.Command.pair; import static io.typst.command.StandardArguments.*; // Define command hierarchy interface ServerCommand { interface PlayerCommand extends ServerCommand { record Kick(String player, String reason) implements PlayerCommand {} record Ban(String player) implements PlayerCommand {} } interface WorldCommand extends ServerCommand { record Load(String worldName) implements WorldCommand {} record Unload(String worldName) implements WorldCommand {} } record Reload() implements ServerCommand {} } // Build nested command structure Command serverCmd = Command.mapping( pair("player", Command.mapping( pair("kick", Command.argument(ServerCommand.PlayerCommand.Kick::new, strArg, strArg)), pair("ban", Command.argument(ServerCommand.PlayerCommand.Ban::new, strArg)) )), pair("world", Command.mapping( pair("load", Command.argument(ServerCommand.WorldCommand.Load::new, strArg)), pair("unload", Command.argument(ServerCommand.WorldCommand.Unload::new, strArg)) )), pair("reload", Command.present(new ServerCommand.Reload())) ); // Parse nested command Either, CommandSuccess> result = Command.parse(new String[]{"player", "kick", "Notch", "Cheating"}, serverCmd); if (result instanceof Either.Right) { ServerCommand cmd = ((Either.Right>) result) .getRight().getCommand(); if (cmd instanceof ServerCommand.PlayerCommand.Kick kick) { System.out.println("Kicking " + kick.player() + " for: " + kick.reason()); } } ``` -------------------------------- ### Define Math Commands with Scala Implicit Arguments Source: https://context7.com/typst-io/command/llms.txt Illustrates defining a sealed trait for math commands (Add, Multiply, Power) using Scala's implicit argument system for type-safe command definitions. It showcases parsing commands and pattern matching on the results. Custom implicit arguments like 'positiveIntArg' are also demonstrated. ```scala import io.typst.command.scala.ScalaCommand._ import io.typst.command.Command sealed trait MathCommand case class Add(a: Int, b: Int) extends MathCommand case class Multiply(a: Int, b: Int, c: Int) extends MathCommand case class Power(base: Double, exponent: Double) extends MathCommand object MathCommands { // Implicit arguments automatically resolve types val mathCmd: Command.Mapping[MathCommand] = mapping( "add" -> argument((a: Int, b: Int) => Add(a, b)), // Uses implicit intArg "mul" -> argument((a: Int, b: Int, c: Int) => Multiply(a, b, c)), "pow" -> argument((base: Double, exp: Double) => Power(base, exp)) // Uses implicit doubleArg ) // Parse command val result = Command.parse(Array("add", "5", "10"), mathCmd) // Pattern match on result result match { case right: io.typst.command.algebra.Either.Right[_, _] => val success = right.getRight.asInstanceOf[io.typst.command.CommandSuccess[MathCommand]] success.getCommand match { case Add(a, b) => println(s"Result: ${a + b}") case Multiply(a, b, c) => println(s"Result: ${a * b * c}") case Power(base, exp) => println(s"Result: ${math.pow(base, exp)}") } case left: io.typst.command.algebra.Either.Left[_, _] => println(s"Parse failed: ${left.getLeft}") } } // Custom implicit argument implicit val positiveIntArg: Argument[Int] = intArg.map(Math.abs) case class SetLevel(level: Int) extends MathCommand val levelCmd = argument((level: Int) => SetLevel(level))(positiveIntArg) ``` -------------------------------- ### Import Command Library with Maven Source: https://github.com/typst-io/command/blob/main/README.md This snippet demonstrates how to include the Typst IO Command library in your Maven project. It defines the dependency with the correct groupId, artifactId, and version. ```xml io.typst command-bukkit 3.1.6 ``` -------------------------------- ### Handle Parsing Errors and Validation in Java Source: https://context7.com/typst-io/command/llms.txt Illustrates how to handle parsing failures and validation errors when using the Typst Command API in Java. It shows how to define a command with arguments, parse invalid input, and differentiate between various failure types like ParsingFailure, UnknownSubCommand, and FewArguments. ```java import io.typst.command.*; import io.typst.command.algebra.Either; import static io.typst.command.Command.pair; import static io.typst.command.StandardArguments.*; record GiveItem(int amount, String itemName) {} Command giveCmd = Command.argument(GiveItem::new, intArg, strArg); // Test various failure scenarios String[] invalidArgs = new String[]{"notANumber", "Diamond"}; Either, CommandSuccess> result = Command.parse(invalidArgs, giveCmd); // Handle different failure types if (result instanceof Either.Left) { CommandFailure failure = ((Either.Left, ?>) result).getLeft(); if (failure instanceof CommandFailure.ParsingFailure pf) { System.out.println("Parsing failed at index: " + pf.getIndex()); System.out.println("Expected arguments: " + pf.getArgs()); // Output: Parsing failed at index: 0 // Expected arguments: [Argument(name=int, ...)] } else if (failure instanceof CommandFailure.UnknownSubCommand uc) { System.out.println("Unknown command: " + uc.getArguments()[uc.getIndex()]); } else if (failure instanceof CommandFailure.FewArguments fa) { System.out.println("Too few arguments provided"); } } ``` -------------------------------- ### Java Command Parsing for Global Variable Update Source: https://github.com/typst-io/command/blob/main/README.md This Java snippet demonstrates a command that updates a global variable and prints output. It highlights a scenario where the command implementation is inlined, which can lead to issues with purity and testing. ```java Command node = Command.mapping( pair("foo", Command.argument(integer -> { GlobalVariables.someVar = integer; System.out.println("Input is: " + integer); // here to break purity return null; }, intArg)) ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.