Commonmark for Java - I want to render without paragraphs?

881 Views Asked by At

I'm using the Atlassian Commonmark API found here to parse Markdown to HTML.
Works beautifully, but tends to add <pand </p>to the beginning and end of every parsed String.

Has anyone used the API extensively in the past and/or has any idea how I could get it to stop doing this?
Other than manually removing the paragraph afterwards, that is, which feels ... unclean somehow.

Edit for clarification: The converted code snippets are intended for use in an HTML table, so I don't need the paragraph bits before and after them.

The Markdown input might be:

####Text for the table here.

The output I'm getting is:

<p><h6>Text for the table here.</h6></p>

What I want is simply for the paragraph snips not to be added:

<h6>Text for the table here.</h6>
1

There are 1 best solutions below

0
On

Was looking for this as well. I achieved it by creating a simple custom renderer that does not render the top level <p>aragraphs.

It checks if the parent of a paragraph is the Document node and if yes it does only render the children of the paragraph.

It extends the default renderer (CoreHtmlNodeRenderer) to get access to visitChildren() and visit(Paragraph)

in kotlin:

class SkipParentWrapperParagraphsRenderer(val context: HtmlNodeRendererContext)
    : CoreHtmlNodeRenderer(context), NodeRenderer {

    override fun getNodeTypes(): Set<Class<out Node>> {
        return setOf(Paragraph::class.java)
    }
    
    override fun render(node: Node) {
        if (node.parent is Document) {
            visitChildren(node)
        } else {
            visit(node as Paragraph)
        }
    }
}

register the new renderer:

val renderer: HtmlRenderer = HtmlRenderer
    .builder()
    .nodeRendererFactory { context -> SkipParentWrapperParagraphsRenderer(context) }
    .build()

There is an example in the documentation.