Suggested way to render Markdown

I am streaming text within a JComponent. This text is formatted as Markdown.

What is the suggested way to render it as such, instead of as plain text?

Does this post help?

1 Like

This looks great, thanks!
I’ll follow-up in there if I have more questions :slight_smile:

import com.intellij.markdown.utils.MarkdownToHtmlConverter;

CommonMarkFlavourDescriptor flavourDescriptor = new CommonMarkFlavourDescriptor();
String html = new MarkdownToHtmlConverter(flavourDescriptor).convertMarkdownToHtml(markdownString, null);

It needs a complete document. I am still looking for a good streaming variant.

1 Like

@vasiliy MarkdownToHtmlConverter is internal.

@insyncwithfoo 's suggestion is better.

DocMarkdownToHtmlConverter.convert(project, someMarkdownString)

That said you may choose whatever lib can convert markdown, we are using the commonmark library to convert it to HTML. And one can customize it as necessary.

val extensions = listOf(TablesExtension.create())
val node = Parser.builder()
    .extensions(extensions)
    .build()
    .parse(markdownString)
HtmlRenderer.builder()
    .nodeRendererFactory { context -> CodeBlockNodeRenderer(project, context) }
    .extensions(extensions)
    .build()
    .render(node, this)

CodeBlockNodeRenderer as its name suggest convert a code block to stylized html, using HtmlSyntaxInfoUtil.appendHighlightedByLexerAndEncodedAsHtmlCodeSnippet behind the scene.

And, to render it I suggest the use of the JBHtmlPane. It’s a glorified JEditorPane with numerous fixes to support basic but good looking HTML, and that’s what powers numerous rendering in IJ, including documentation.

1 Like

Haven’t gotten to implementing this yet, but I have a follow-up question:

How do I setup the markdown so that files can be clicked to open them as an Editor tab in the IDE?

How do I setup the markdown so that files can be clicked […]

As in, links to files? If so, you can use a custom URI (say, yourplugin:///file.identifier/something#something) for the target, then extend com.intellij.platform.backend.documentation.linkHandler to handle such links however you want.

1 Like