Last active
September 12, 2024 16:08
-
-
Save fjfish/12b9f2bbdc80ce0702e8b033ff702c20 to your computer and use it in GitHub Desktop.
Kotlin code to create annotated string for bold markdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.