Skip to content

Instantly share code, notes, and snippets.

@TBlueF
Last active January 4, 2020 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TBlueF/bd60d2e4ae9e76c32733dd6d4a9ed34a to your computer and use it in GitHub Desktop.
Save TBlueF/bd60d2e4ae9e76c32733dd6d4a9ed34a to your computer and use it in GitHub Desktop.
A replace util function for Sponge's Text
package de.bluecolored.spongeutil;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.spongepowered.api.text.LiteralText;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.TextRepresentable;
import org.spongepowered.api.text.action.HoverAction;
import org.spongepowered.api.text.action.HoverAction.ShowText;
import org.spongepowered.api.text.action.TextActions;
public class TextUtils {
public static Text replace(Text haystack, String needle, Object replacement){
//prepare builder
Text.Builder b = haystack.toBuilder();
//prepare children
List<Text> childs = new ArrayList<>();
childs.addAll(b.getChildren());
b.removeAll();
//replace hover
Optional<HoverAction<?>> ha = b.getHoverAction();
if (ha.isPresent() && ha.get() instanceof ShowText){
ShowText st = (ShowText) ha.get();
Text newHover = replace(st.getResult(), needle, replacement);
b.onHover(TextActions.showText(newHover));
}
//prepare replacement
Text replacementText = null;
if (replacement instanceof TextRepresentable){
replacementText = ((TextRepresentable) replacement).toText();
}
//modify plain
if (b instanceof LiteralText.Builder){
LiteralText.Builder lb = (LiteralText.Builder) b;
if (replacementText == null){
String newContent = lb.getContent().replace(needle, replacement.toString());
lb.content(newContent);
} else {
String cont = lb.getContent();
lb.content("");
List<Text> parts = new ArrayList<>(3);
Matcher m = Pattern.compile(Pattern.quote(needle)).matcher(cont);
int pointer = 0;
while(m.find()){
if (m.start() > pointer){
parts.add(Text.of(cont.substring(pointer, m.start())));
}
parts.add(replacementText);
pointer = m.end();
}
if (cont.length() > pointer){
parts.add(Text.of(cont.substring(pointer, cont.length())));
}
lb.append(parts);
}
}
//add children back
for (Text c : childs){
b.append(replace(c, needle, replacement));
}
return b.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment