kotmark

A Markdown engine
Kotlin Multiplatform

Extension 10 / kotmark-ext-math

Math

Kotmark preserves formula text and emits semantic wrappers; rendering equations is left to the host application.

Artifact
io.heapy.kotmark:kotmark-ext-math:0.1.0
Package
io.heapy.kotmark.ext.math

Usage

Enable inline and block math
import io.heapy.kotmark.ext.math.math
import io.heapy.kotmark.extensions
import io.heapy.kotmark.parser.parser
import io.heapy.kotmark.renderer.html.htmlRenderer

fun renderWithMath(markdown: String): String {
    val extensions = extensions { math() }
    val document = parser { extensions(extensions) }.parse(markdown)
    // Formula source is escaped and wrapped; no TeX engine is involved.
    return htmlRenderer { extensions(extensions) }.render(document)
}

Example

INPUT · Markdown
Energy: $E=mc^2$.

$$
\sum_{k=1}^n a_k^2
$$
OUTPUT · HTML
<p>Energy: <span class="math math-inline">E=mc^2</span>.</p>
<div class="math math-block">\sum_{k=1}^n a_k^2
</div>

Custom HTML output

Override the extension's default math node renderer to emit <code> elements or connect a client-side math renderer.

Render formulas as code
import io.heapy.kotmark.ext.math.InlineMath
import io.heapy.kotmark.ext.math.MathBlock
import io.heapy.kotmark.ext.math.math
import io.heapy.kotmark.extensions
import io.heapy.kotmark.renderer.html.HtmlRenderer
import io.heapy.kotmark.renderer.html.htmlRenderer
import io.heapy.kotmark.renderer.html.nodeRenderer

fun mathAsCodeRenderer(): HtmlRenderer {
    val extensions = extensions { math() }
    return htmlRenderer {
        // Register the overrides before the extension: the first renderer wins.
        nodeRenderer<InlineMath> { math ->
            writer.tag("code", mapOf("class" to "tex"))
            writer.text(math.literal)
            writer.tag("/code")
        }
        nodeRenderer<MathBlock> { math ->
            writer.tag("code", mapOf("class" to "tex"))
            writer.text(math.literal)
            writer.tag("/code")
        }
        extensions(extensions)
    }
}
INPUT · Markdown
Energy: $E=mc^2$.
OUTPUT · HTML
<p>Energy: <code class="tex">E=mc^2</code>.</p>