https://kotlinlang.org logo
Title
m

Marcin Wisniowski

03/26/2023, 4:38 PM
I need to render Markdown in Compose (on Android). Does anyone have any recommendation for a library or solution? I'm currently considering this library: https://github.com/jeziellago/compose-markdown Or using this JetBrains library for parsing the Markdown: https://github.com/JetBrains/markdown and writing the Compose code myself to render the parsed text. Does anyone have any insight?
o

orangy

03/26/2023, 5:44 PM
We have pretty sophisticated code to render markdown, because we support tables and code blocks, quotes, paragraph spacing, etc. Unfortunately I can’t share it, but what I mean if you want to implement it yourself be prepared to invest quite some time.
m

Marcin Wisniowski

03/26/2023, 6:08 PM
I'm controlling the input Markdown, and should only need to support bold, italics, and headings, so I am assuming it wouldn't be that bad to implement.
o

orangy

03/26/2023, 6:11 PM
Yeah, in that case any markdown parser and AnnotatedString would work just fine and easy. But if you generate it or it’s some internal representation of rich text, consider more specific format that you can parse unambiguously
c

Colton Idle

03/26/2023, 6:52 PM
@Halil Ozercan didn't you have a markdown parser in compose?
m

Mark Murphy

03/26/2023, 7:40 PM
m

Marcin Wisniowski

03/26/2023, 8:09 PM
That looks promising, thank you.
h

Halil Ozercan

03/26/2023, 10:43 PM
If your requirement is just to convert text styling of markdown into AnnotatedString, Richtext commonmark library can be an overkill. Please take a look at
computeRichTextString
function here. https://github.com/halilozercan/compose-richtext/blob/3c5b38f51e824bd88d6e5785fd90[…]nMain/kotlin/com/halilibo/richtext/markdown/MarkdownRichText.kt Although it returns RichTextString, not AnnotatedString,
computeRichTextString
can give you a general idea of how to accomplish your goal. It's a preorder traversal of markdown tree that commonmark produces. While traversing you can simply build an AnnotatedString node by node.
m

Marcin Wisniowski

04/24/2023, 9:34 AM
I ended up using https://github.com/commonmark/commonmark-java to parse the Markdown, then traverse the AST to build an AnnotatedString, similar to Halil's example. Works fine.