这是我写的一个小助手类,如果当前行以给定的后缀结尾,它将保持缩进甚至增加缩进一级。它使用 RichTextFX 的 InputMap-API。
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.fxmisc.richtext.GenericStyledArea;
import org.fxmisc.wellbehaved.event.EventPattern;
import org.fxmisc.wellbehaved.event.InputMap;
import org.fxmisc.wellbehaved.event.Nodes;
import javafx.scene.input.KeyCode;
public class RichTextFXAutoIndenter {
private static final Pattern LEADING_WHITESPACE = Pattern.compile( "^\\s+" );
public static void install(GenericStyledArea<?, String, ?> genericStyledArea, String ... indentSuffixes) {
Nodes.addInputMap(genericStyledArea, InputMap.consume(EventPattern.keyPressed(KeyCode.ENTER), event -> enterPressed(genericStyledArea, indentSuffixes)));
}
private static void enterPressed(GenericStyledArea<?, String, ?> genericStyledArea, String[] indentSuffixes) {
genericStyledArea.replaceSelection("\n" + getIndentation(genericStyledArea, indentSuffixes));
}
private static String getIndentation(GenericStyledArea<?, String, ?> genericStyledArea, String[] indentSuffixes) {
String currentLine = genericStyledArea.getParagraph(genericStyledArea.getCurrentParagraph()).getSegments().get(0);
Matcher m = LEADING_WHITESPACE.matcher(currentLine);
String indent = "";
if (m.find()) {
indent = m.group();
}
if (Arrays.stream(indentSuffixes).anyMatch(suffix -> currentLine.trim().endsWith(suffix))) {
indent += "\t";
}
return indent;
}
}