Skip to content

Instantly share code, notes, and snippets.

@fjfish
Last active September 12, 2024 16:08
Show Gist options
  • Save fjfish/12b9f2bbdc80ce0702e8b033ff702c20 to your computer and use it in GitHub Desktop.
Save fjfish/12b9f2bbdc80ce0702e8b033ff702c20 to your computer and use it in GitHub Desktop.
Kotlin code to create annotated string for bold markdown
// Text may contain bold markdown so let's make it work
fun formattedText(text: String): AnnotatedString {
// Bold ** - only one we care about right now
val boldPieces = text.split(Regex("\\*\\*"))
if (boldPieces.size == 1) {
return AnnotatedString(text)
}
// This does not work if the string begins with **
return buildAnnotatedString {
var toggleBoldOff = false
pushStyle(SpanStyle(fontWeight = FontWeight.Normal))
for (piece in boldPieces) {
append(piece)
if (toggleBoldOff) {
pop()
toggleBoldOff = false
} else {
pushStyle(SpanStyle(fontWeight = FontWeight.Bold))
toggleBoldOff = true
}
}
}
}
@fjfish
Copy link
Author

fjfish commented Sep 12, 2024

This is short and sweet and met my needs. You could probably adapt this to write a function for italic and so on if you wanted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment