-
Notifications
You must be signed in to change notification settings - Fork 3
Add custom tags and markups
This page is a step-by-step guide on how to add custom tags and markups.
First things first, it's required to specify the tags. The pattern is a regular expression that parser will use to match the text content. In our example, we will create 2 patterns:
val PATTERN_HIGHLIGHT_BLUE = Pattern.compile("^<hl-blue>([\s\S]+?)<\/hl-blue>")
val PATTERN_HEADER = Pattern.compile("^<h1>([\s\S]+?)</h1>")
⚠ Make sure you add plain text pattern to parse text that is now marked with any tags.
So we will also add text pattern:
val PATTERN_TEXT = Pattern.compile"^[\\s\\S]+?(?=[^0-9A-Za-z\\s\\u00c0-\\uffff]|\\n| {2,}\\n|\\w+:\\S|$)"
A rule collects information about:
- What text content should be collected (using the pattern)
- How it should be styled (storing styling configuration in
decoration
property) - What node will be created when the content gets parsed
To create a rule simply use one of the extensions:
val rules = listOf(
PATTERN_HIGHLIGHT_BLUE.toRule(),
PATTERN_HEADER.toRule(),
PATTERN_TEXT.toRule()
)
⚠ Plain text pattern should be last in the list. Parser tries to match the content with all patterns one by one. If none were matched - it will simply get it as plain text. However, if plain text pattern was at top, than parser would simply get every segment as plain text never coming to other patterns.
To add a style that will be applied to the matched content simply add it as a parameter to rule extension:
val rules = listOf(
PATTERN_HIGHLIGHT_BLUE.toRule(SpanStyle(color = Color.Blue),
PATTERN_HEADER.toRule(SpanStyle(fontSize = 20.sp, color = Color.Gray, fontWeight = FontWeight.Bold))
)
Create a SimpleMarkupParser instance to parse the content. Get custom rules. Execute parse()
function passing a source text to it along with custom rules.
val parser = SimpleMarkupParser()
val rules = listOf(
PATTERN_HIGHLIGHT_BLUE.toRule(SpanStyle(color = Color.Blue),
PATTERN_HEADER.toRule(SpanStyle(fontSize = 20.sp, color = Color.Gray, fontWeight = FontWeight.Bold))
)
val content = parser
.parse(source, rules)
.render()
.toAnnotatedString()
Parser will go through text with each rule one by one trying to find matches in it.