Text formatter feature holds formatters for different text formats allowing generating (X)HTML code from various source types.
Central class for text processing is pl.wrzasq.commons.text.TextFormatter - it aggregates multiple format handlers. You can use its instance to format source text in any registered format:
val formatter = Formatter()
formatter.registerFormatter("plain", PlainTextFormatter())
formatter.registerFormatter("html", HtmlFormatter())
formatter.registerFormatter("markdown", MarkdownFormatter())
// formats using plain text
val plainText = formatter.format("plain", "<foo bar>")
// formats using HTML
val html = formatter.format("html", "<p>foo</p>")
// formats using Markdown
val markdown = formatter.format("markdown", "**foo**")
// throws exception because of unknown format
val unknown = formatter.format("unknown", "foo")
Handled by pl.wrzasq.commons.text.formatter.PlainTextFormatter. It returns HTML snippet that with all HTML special characters replaced by entities to avoid their interpretation. Also replaces new line characters with <br/> to map all lines.
val formatHandler = PlainTextFormatter()
// generates "foo <bar><br/>baz"
formatHandler.transform("foo <bar>\nbaz")
Handled by pl.wrzasq.commons.text.formatter.HtmlFormatter. Since we operate in (X)HTML by default this formatter does literally nothing - returns input text untouched.
val formatHandler = HtmlFormatter()
// returns same input text
formatHandler.transform("foo <bar>\nbaz")
Handled by pl.wrzasq.commons.text.formatter.MarkdownFormatter. Formats Markdown into HTML. It uses Pegdown with all available extensions.
val formatHandler = MarkdownFormatter()
// genrates "<p><strong>foo</strong> <em>bar</em></p>"
formatHandler.transform("**foo** _bar_")
Apart from existing formatters there is an interface pl.wrzasq.commons.text.formatter.FormatterInterface. It can be used for implementing any custom format handler:
class MyTextFormatter : FormatterInterface {
fun transform(text: String): String {
return "<p>" + text.replaceAll("\n", "</p><p>") + "</p>"
}
}