### Placeholder API Developer Documentation Source: https://placeholders.pb4.eu/dev/getting-started Documentation for developers on using the Placeholder API, including adding and parsing placeholders, and working with text nodes. ```APIDOC Placeholder API Developer Guide: Getting Started: - Provides an overview for developers. Adding Placeholders: - Details on how to contribute new placeholders to the API. Parsing Placeholders: - Explains the process and methods for parsing placeholder syntax. Text Nodes and Node Parsers: - Describes the architecture involving Text Nodes and custom Node Parsers for advanced customization. Using Simplified Text Format/TextParser: - Information on leveraging the Simplified Text Format and the TextParser utility for efficient text processing. ``` -------------------------------- ### Declare placeholder-api Dependency Source: https://placeholders.pb4.eu/dev/getting-started Add the placeholder-api library as a dependency to your project. Replace `[VERSION]` with the desired version. This ensures your project can utilize the placeholder functionalities. Examples are provided for both Groovy and Kotlin build scripts. ```groovy dependencies{ // You will have other dependencies here too modImplementationinclude("eu.pb4:placeholder-api:[VERSION]") } ``` ```kotlin dependencies{ // You will have other dependencies here too modImplementation(include("eu.pb4:placeholder-api:[VERSION]")) } ``` -------------------------------- ### Add Nucleoid Maven Repository Source: https://placeholders.pb4.eu/dev/getting-started Configure your build file to include the Nucleoid maven repository. This allows Gradle to find and download the placeholder-api library. This snippet shows how to add the repository for both Groovy and Kotlin build scripts. ```groovy repositories{ // There might be other repos there too, just add it at the end maven{url"https://maven.nucleoid.xyz/" name"Nucleoid" } } ``` ```kotlin repositories{ // There might be other repos there too, just add it at the end maven("https://maven.nucleoid.xyz/"){name="Nucleoid"} } ``` -------------------------------- ### Java Node Parser Example with Player Context Source: https://placeholders.pb4.eu/dev/text-nodes Demonstrates how to use Node Parsers in Java with player context. It shows merging parsers, parsing text nodes with placeholders, and converting the output to formatted text. ```java publicclass Example{ // With player context publicstaticvoidexampleContext(ServerPlayerEntityplayer){ NodeParserparser=NodeParser.merge(TextParserV1.DEFAULT,Placeholders.DEFAULT_PLACEHOLDER_GETTER); TextNodeoutput=parser.parseNode("Hello %player:name%"); // or TextNodeoutput=parser.parseNode(TextNode.of("Hello %player:name%")); // or (only way before 2.0.0-beta.4) TextNodeoutput=TextNode.asSingle(parser.parseNodes(TextNode.of("Hello %player:name%"))); Texttext=output.toText(PlaceholderContext.of(player)); // or Texttext=output.toText(PlaceholderContext.of(player).asParserContext()); // or Texttext=output.toText(ParserContext.of().with(PlaceholderContext.KEY,PlaceholderContext.of(player))); // or (only way before 2.0.0-beta.4) Texttext=output.toText(PlaceholderContext.of(player).asParserContext(),true); } // Without context publicstaticvoidexample(){ NodeParserparser=NodeParser.merge(TextParserV1.DEFAULT,Placeholders.DEFAULT_PLACEHOLDER_GETTER); TextNodeoutput=parser.parseNode("Hello user!"); Texttext=output.toText(); // or Texttext=output.toText(ParserContext.of()); // or (only way before 2.0.0-beta.4) Texttext=output.toText(ParserContext.of(),true); } } ``` -------------------------------- ### Kotlin Placeholder Parsing Example Source: https://placeholders.pb4.eu/dev/parsing-placeholders Demonstrates parsing dynamic placeholders in a Kotlin function. It handles player names and random numbers, allowing for custom formatting and arguments. ```kotlin objectDynamicPlaceholders{ privatevalrandom=Random() /** * Example input: * ``` * Hello! ${player blue}. Random number between 0 and 20: ${random 20} * ``` * * Example output: * ``` * Hello! ThePlayerName. Random number: 13 * ``` */ funparseInputText(player:ServerPlayerEntity,inputText:Text):Text{ // parse the inputText message returnPlaceholders.parseText(inputText,PlaceholderContext.of(player), Placeholders.PREDEFINED_PLACEHOLDER_PATTERN, DynamicPlaceholders::getPlaceholder) } privatefungetPlaceholder(id:String):PlaceholderHandler? { returnwhen(id){ "player"->PlaceholderHandler(DynamicPlaceholders::playerPlaceholder) "random"->PlaceholderHandler(DynamicPlaceholders::randomPlaceholder) else->null } } privatefunplayerPlaceholder(ctx:PlaceholderContext,arg:String?):PlaceholderResult{ if(arg==null) returnPlaceholderResult.invalid("No argument!") if(ctx.player==null) returnPlaceholderResult.value( Text.literal("You are not a player!") .setStyle(Style.EMPTY.withColor(TextColor.parse(arg))) ) returnPlaceholderResult.value( ctx.player!!.name.copy() .setStyle(Style.EMPTY.withColor(TextColor.parse(arg))) ) } privatefunrandomPlaceholder(ctx:PlaceholderContext,arg:String?):PlaceholderResult{ returntry{ valrandomNumber=random.nextInt(arg?.toInt()?:10) PlaceholderResult.value(randomNumber.toString()) }catch(e:NumberFormatException){ PlaceholderResult.invalid("Invalid number!") } } } ``` -------------------------------- ### Placeholder Context Variants Source: https://placeholders.pb4.eu/dev/parsing-placeholders Explains the different variants of `PlaceholderContext.of(...)` and the types of placeholders they enable. Each variant specifies dependencies on server, command source, player, world, entity, and game profile. ```APIDOC PlaceholderContext.of(...) Variants: - MinecraftServer: - May use placeholders that depend on the server - May use placeholders that depend on ServerCommandSource (Note: uses the command source from MinecraftServer.getCommandSource()) - GameProfile: - May use placeholders that depend on the server - May use placeholders that depend on ServerCommandSource (Note: creates a new dummy command source at (0,0,0)) - May use placeholders that depend on GameProfile - ServerPlayerEntity: - May use placeholders that depend on the server - May use placeholders that depend on ServerCommandSource - May use placeholders that depend on ServerWorld - May use placeholders that depend on ServerPlayerEntity - May use placeholders that depend on Entity - May use placeholders that depend on GameProfile - ServerCommandSource: - May use placeholders that depend on the server - May use placeholders that depend on ServerCommandSource - May use placeholders that depend on ServerWorld - May use placeholders that depend on ServerPlayerEntity _only if the source has a player_ - May use placeholders that depend on Entity _only if the source has an entity_ - May use placeholders that depend on GameProfile _only if the source has a player_ - Entity: - May use placeholders that depend on the server - May use placeholders that depend on ServerCommandSource - May use placeholders that depend on ServerWorld - May use placeholders that depend on ServerPlayerEntity _only if the source has a player_ - May use placeholders that depend on Entity - May use placeholders that depend on GameProfile _only if the source has a player_ ``` -------------------------------- ### PlaceholderAPI Patterns Source: https://placeholders.pb4.eu/dev/parsing-placeholders Lists and describes the available static patterns for placeholder identification in PlaceholderAPI, explaining their usage and potential for collisions. ```APIDOC PlaceholderAPI Patterns: - Placeholders.PREDEFINED_PLACEHOLDER_PATTERN (`${placeholder}`): Recommended for most cases, minimizes collisions. - Placeholders.ALT_PLACEHOLDER_PATTERN_CUSTOM (`{placeholder}`): Alternative, higher chance of colliding with user formatting. - Placeholders.PLACEHOLDER_PATTERN_CUSTOM (`%placeholder%`): Similar to default, but does not require a colon. - Placeholders.PLACEHOLDER_PATTERN (`%category:placeholder%`): Default for global placeholders, requires a category. - Placeholders.PLACEHOLDER_PATTERN_ALT (`{category:placeholder}`): Alternative format for global placeholders, requires a category. ``` -------------------------------- ### Registering a New Placeholder Source: https://placeholders.pb4.eu/dev/adding-placeholders Demonstrates how to register a new placeholder using the `Placeholders.register` method. This involves providing a unique identifier and a function that returns a `PlaceholderResult`. The function accepts a `PlaceholderContext` and an optional string argument. ```java Placeholders.register( newIdentifier("example","placeholder"), (ctx,arg)->PlaceholderResult.value(Text.literal("Hello World!")) ); ``` -------------------------------- ### PlaceholderResult Creation Source: https://placeholders.pb4.eu/dev/adding-placeholders Demonstrates how to create PlaceholderResult instances for successful and invalid returns using static methods. Successful returns use `PlaceholderResult.value()` with Text or String inputs, while invalid returns use `PlaceholderResult.invalid()` with an optional reason. ```python from placeholders import PlaceholderResult, Text, String # Successful returns result_text = PlaceholderResult.value(Text("some text")) result_string = PlaceholderResult.value(String("another text")) # Invalid returns invalid_result = PlaceholderResult.invalid() invalid_result_with_reason = PlaceholderResult.invalid("Invalid player or argument") ``` -------------------------------- ### Registering a New Placeholder (Kotlin) Source: https://placeholders.pb4.eu/dev/adding-placeholders Shows the Kotlin equivalent of registering a new placeholder. The syntax is similar, utilizing lambda expressions for the placeholder function. ```kotlin Placeholders.register(Identifier("example","placeholder")){ctx,arg-> PlaceholderResult.value(Text.literal("Hello World!")) } ``` -------------------------------- ### Parse Text with TextParserUtils Source: https://placeholders.pb4.eu/dev/text-format Demonstrates how to use the `TextParserUtils.parseText` method to format a given input string. This method handles the parsing of placeholders and tags within the string, returning a formatted Text object. It's suitable for admin-provided configurations. ```java String inputString="Hello World!" Text output=TextParserUtils.parseText(inputString); ``` -------------------------------- ### Parse Text with Selected Tags Source: https://placeholders.pb4.eu/dev/text-format Shows how to parse text using only a selected set of tags. This is achieved by retrieving the default tags using `TextParserV1.DEFAULT.getTags()` and then passing this selection to the `TextParserUtils.parseText` method along with the input string. ```java String inputString = "Hello World!"; TextParserV1.TagParserGetter selectedTags = TextParserV1.DEFAULT.getTags(); Text output = TextParserUtils.parseText(inputString, selectedTags); ``` -------------------------------- ### Parse Text with TextParserUtils (Kotlin) Source: https://placeholders.pb4.eu/dev/text-format Demonstrates how to use the `TextParserUtils.parseText` method in Kotlin to format a given input string. This method handles the parsing of placeholders and tags within the string, returning a formatted Text object. It's suitable for admin-provided configurations. ```kotlin val inputString="Hello World!" val output=TextParserUtils.parseText(inputString); ``` -------------------------------- ### Dynamic Placeholder Parsing in Java Source: https://placeholders.pb4.eu/dev/parsing-placeholders Demonstrates the process of parsing text with dynamic placeholders in Java. This involves setting up a map of identifiers to PlaceholderHandlers and a pattern object, then utilizing the `parseText` method with a specific context. ```java Map dynamicPlaceholders = new HashMap<>(); // Add your dynamic placeholders here Pattern pattern = new Pattern(); // Configure your pattern PlaceholderContext context = new PlaceholderContext(); // Configure your context String textToParse = "Your text with placeholders"; String parsedText = PlaceholderParser.parseText(textToParse, context, pattern, dynamicPlaceholders); ``` -------------------------------- ### Java ColorNode Implementation Source: https://placeholders.pb4.eu/dev/text-nodes Demonstrates the implementation of a ColorNode in Java, which extends ParentNode to apply specific text colors. It includes methods for applying formatting, creating copies with children, and optionally with a parser. ```java public final class ColorNode extends ParentNode { private final TextColor color; public ColorNode(TextNode[] children, TextColor color) { super(children); this.color = color; } @Override protected Text applyFormatting(MutableText out, ParserContext context) { return out.setStyle(out.getStyle().withColor(this.color)); } @Override public ParentTextNode copyWith(TextNode[] children) { return new ColorNode(children, this.color); } // This one should be only override if you have dynamic sub-values, like HoverNode @Override public ParentTextNode copyWith(TextNode[] children, NodeParser parser) { return new ColorNode(children, this.color); } } ``` -------------------------------- ### Parse Global Placeholders (Java) Source: https://placeholders.pb4.eu/dev/parsing-placeholders Parses global placeholders from a given text input using the `Placeholders.parseText` method. It requires a `PlaceholderContext` and returns a parsed `Text` object. This method uses the default `%category:placeholder%` formatting. ```java TextMessage = Placeholders.parseText(textInput, PlaceholderContext.of(...)); ``` -------------------------------- ### Register Placeholder Requiring Player (Java) Source: https://placeholders.pb4.eu/dev/adding-placeholders Registers a placeholder that requires a player context. If no player is present, it returns an invalid result. Otherwise, it returns the player's display name. ```Java Placeholders.register(newIdentifier("player","displayname"),(ctx,arg)->{ if(!ctx.hasPlayer()) returnPlaceholderResult.invalid("No player!"); returnPlaceholderResult.value(ctx.getPlayer().getDisplayName()); }); ``` -------------------------------- ### Parse Placeholders with Custom Pattern (Java) Source: https://placeholders.pb4.eu/dev/parsing-placeholders Parses placeholders from a given text input using a custom pattern. This method allows for flexible placeholder formatting beyond the default `%category:placeholder%`. It requires the text, a `PlaceholderContext`, and a `Pattern` object. ```java Placeholders.parseText(Text, PlaceholderContext, Pattern); ``` -------------------------------- ### Kotlin Dynamic Placeholder Parsing Source: https://placeholders.pb4.eu/dev/parsing-placeholders Provides a Kotlin implementation for parsing dynamic placeholders in text. It mirrors the Java functionality, handling player names and random number generation with similar logic and dependencies. ```kotlin 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 ``` -------------------------------- ### Java Dynamic Placeholder Parsing Source: https://placeholders.pb4.eu/dev/parsing-placeholders Parses input text to replace dynamic placeholders with contextual information. It handles player names and random number generation. Dependencies include the Placeholders class and PlaceholderContext. ```java public class DynamicPlaceholders { private static final Random random = new Random(); /** * Example input: * * Hello! ${player blue}. Random number between 0 and 20: ${random 20} * * * Example output: * * Hello! ThePlayerName. Random number: 13 * */ public static Text parseInputText(ServerPlayerEntity player, Text inputText) { // parse the inputText message return Placeholders.parseText(inputText, PlaceholderContext.of(player), Placeholders.PREDEFINED_PLACEHOLDER_PATTERN, DynamicPlaceholders::getPlaceholder); } private static PlaceholderHandler getPlaceholder(String id) { return switch (id) { case "player" -> DynamicPlaceholders::playerPlaceholder; case "random" -> DynamicPlaceholders::randomPlaceholder; default -> null; }; } private static PlaceholderResult playerPlaceholder(PlaceholderContext ctx, String arg) { if (arg == null) return PlaceholderResult.invalid("No argument!"); if (!ctx.hasPlayer()) return PlaceholderResult.value( Text.literal("You are not a player!") .setStyle(Style.EMPTY.withColor(TextColor.parse(arg))) ); return PlaceholderResult.value( ctx.player().getName().copy() .setStyle(Style.EMPTY.withColor(TextColor.parse(arg))) ); } private static PlaceholderResult randomPlaceholder(PlaceholderContext ctx, String arg) { if (arg == null) { int randomNumber = random.nextInt(10); return PlaceholderResult.value(String.valueOf(randomNumber)); } try { int randomNumber = random.nextInt(Integer.parseInt(arg)); return PlaceholderResult.value(String.valueOf(randomNumber)); } catch (NumberFormatException e) { return PlaceholderResult.invalid("Invalid number!"); } } } ``` -------------------------------- ### Placeholder API - TextNode Types and Parsers Source: https://placeholders.pb4.eu/dev/text-nodes Provides an overview of the Placeholder API's text processing components, including different types of TextNodes (LiteralNode, TranslationNode, DirectTextNode, PlaceholderNode) and the concept of Node Parsers for handling custom text formats and placeholders. ```APIDOC TextNode Types: - LiteralNode: Used for direct text, requires special parsing by parsers. - TranslationNode: Used for translated text, also requires special parsing. - DirectTextNode: Allows insertion of non-transformable text, usable for static placeholders. - PlaceholderNode (Internal): Represents a parsed placeholder without its final value. Node Parsers: - Parsers operate on the lowest level of TextNodes. - Custom Node Parsers can be implemented by adhering to the TextNode interface. ``` -------------------------------- ### Register Placeholder with UUID Argument (Kotlin) Source: https://placeholders.pb4.eu/dev/adding-placeholders Registers a placeholder in Kotlin that takes a UUID argument to fetch a player's name. It includes error handling for missing arguments and invalid UUIDs. ```Kotlin PlaceholderAPI.register(Identifier("server","name_from_uuid")){ctx,arg-> if(arg==null) returnPlaceholderResult.invalid("No argument!") valuuid=UUID.fromString(arg) valplayer=ctx.server().userCache.getByUuid(uuid).get() returnPlaceholderResult.value(player.name) } ``` -------------------------------- ### Parse Global Placeholders (Kotlin) Source: https://placeholders.pb4.eu/dev/parsing-placeholders Parses global placeholders from a given text input using the `Placeholders.parseText` method in Kotlin. It requires a `PlaceholderContext` and returns a parsed `Text` object. This method uses the default `%category:placeholder%` formatting. ```kotlin val message = Placeholders.parseText(textInput, PlaceholderContext.of(...)) ``` -------------------------------- ### Register Placeholder Requiring Player (Kotlin) Source: https://placeholders.pb4.eu/dev/adding-placeholders Registers a placeholder that requires a player context in Kotlin. It checks for player presence and returns the display name or an invalid result. ```Kotlin Placeholders.register(Identifier("player","displayname")){ctx,args-> if(!ctx.hasPlayer()) returnPlaceholderResult.invalid("No player!") PlaceholderResult.value(ctx.player!!.displayName) } ``` -------------------------------- ### Register Placeholder with UUID Argument (Java) Source: https://placeholders.pb4.eu/dev/adding-placeholders Registers a placeholder that accepts a UUID as an argument to retrieve a player's name. It handles cases where the argument is missing or the UUID is invalid. ```Java PlaceholderAPI.register(newIdentifier("server","name_from_uuid"),(ctx,arg)->{ if(arg==null) returnPlaceholderResult.invalid("No argument!"); UUIDuuid=UUID.fromString(arg); GameProfileplayer=ctx.server().getUserCache().getByUuid(UUID.fromString(arg)).get() returnPlaceholderResult.value(player.getName())); }); ``` -------------------------------- ### DirectTextNode Implementation in Java Source: https://placeholders.pb4.eu/dev/text-nodes Demonstrates the implementation of a DirectTextNode in Java, a type of Value Text Node used for inserting non-transformable text. This node can be utilized for static placeholders and requires special parsing. ```Java publicrecord DirectTextNode(Texttext)implementsTextNode{ @Override publicTexttoText(ParserContextcontext,booleanremoveBackslash){ returnthis.text; } } ``` -------------------------------- ### Format Player Message Source: https://placeholders.pb4.eu/dev/parsing-placeholders Formats a player message by replacing placeholders in the input text with provided player name and message content. It supports replacing `${playerName}` and `${message}`. ```kotlin objectStaticPlaceholders{ /** * Formats a player message according to [inputText] * * Example input: * ``` * ${playerName} says "${message}"! * ``` * * @param inputText The text that is parsed for placeholders. * Example input: * `${playerName} says "${message}"` * * @param player The player name used to replace the `${playerName}` variable in the input. * Example input: * the player who's name is `ThePlayerUsername` * * @param messageText The text used to replace the `${message}` variable in the input. * Example input: * `this is the message` * * @return The formatted message. * Example return: * ``` * ThePlayerUsername says "this is the message"! * ``` */ funformatPlayerMessage(inputText:Text?,player:ServerPlayerEntity,messageText:Text):Text{ valplaceholders=mapOf( "message"tomessageText, // replace ${message} with the messageText "playerName"toplayer.name, // replace ${playerName} with the player's name ) returnPlaceholders.parseText(inputText,Placeholders.PREDEFINED_PLACEHOLDER_PATTERN, placeholders) // parse the inputText } } ``` -------------------------------- ### Format Player Message in Kotlin Source: https://placeholders.pb4.eu/dev/parsing-placeholders Formats a player message by replacing placeholders like ${playerName} and ${message} with provided values. It utilizes a Map for placeholder replacements and the PlaceholderAPI's parseText method. ```kotlin publicclass StaticPlaceholders{ /** * Formats a player message according to inputText * * Example input: * * ${playerName} says "${message}" * * * @param inputText The text that is parsed for placeholders. * Example input: * ${playerName} says "${message}" * @param player The player name used to replace the ${playerName} * variable in the input. Example input: * the player who's name is 'ThePlayerUsername' * @param messageText The message text used to replace the ${message} * variable in the input. Example input: * this is the message * * @return The formatted message. Example return: * ThePlayerUsername says "this is the message" */ publicstaticTextformatPlayerMessage(TextinputText,ServerPlayerEntityplayer, TextmessageText){ Mapplaceholders=Map.of( "message",messageText,// replace ${message} with the messageText "playerName",player.getName()// replace ${playerName} with the player's name ); returnPlaceholders.parseText(inputText, Placeholders.PREDEFINED_PLACEHOLDER_PATTERN, placeholders);// parse the inputText } } ``` -------------------------------- ### Java Custom Node Parser Implementation Source: https://placeholders.pb4.eu/dev/text-nodes This Java code implements a custom NodeParser to handle LiteralNode, TranslatedNode, and ParentNode. It demonstrates how to modify node values, process arguments, and manage child nodes. ```java publicrecord ExampleParser()implementsNodeParser{ publicTextNode[]parseNodes(TextNodeinput){ if(inputinstanceofLiteralNodenode){ returnTextNode.array(newLiteralNode(node.value().replace("<3","❤️"))); }elseif(inputinstanceofTranslatedNodenode){ varargs=newArrayList<>(); for(vararg:node.args()){ args.add(arginstanceofTextNodeargNode?this.parseNode(argNode):arg); } returnTextNode.array(newTranslatedNode(node.key(),args.toArray())); }elseif(inputinstanceofParentTextNodenode){ varchildren=newArrayList(); for(varchild:parentNode.getChildren()){ children.add(this.parseNode(child)); } returnTextNode.array(parentNode.copyWith(out.toArray(newTextNode[0]),this)); } returnTextNode.array(input); } } ``` -------------------------------- ### Format Player Message in Java Source: https://placeholders.pb4.eu/dev/parsing-placeholders Formats a player message by replacing placeholders like ${playerName} and ${message} with provided values. It uses a Map to store placeholder key-value pairs and the PlaceholderAPI's parseText method. ```java publicclass StaticPlaceholders{ /** * Formats a player message according to inputText * * Example input: * * ${playerName} says "${message}" * * * @param inputText The text that is parsed for placeholders. * Example input: * ${playerName} says "${message}" * @param player The player name used to replace the ${playerName} * variable in the input. Example input: * the player who's name is 'ThePlayerUsername' * @param messageText The message text used to replace the ${message} * variable in the input. Example input: * this is the message * * @return The formatted message. Example return: * ThePlayerUsername says "this is the message" */ publicstaticTextformatPlayerMessage(TextinputText,ServerPlayerEntityplayer, TextmessageText){ Mapplaceholders=Map.of( "message",messageText,// replace ${message} with the messageText "playerName",player.getName()// replace ${playerName} with the player's name ); returnPlaceholders.parseText(inputText, Placeholders.PREDEFINED_PLACEHOLDER_PATTERN, placeholders);// parse the inputText } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.