Extension 06 / kotmark-ext-heading-anchor
Heading anchors
Heading anchors are an HTML-rendering feature; the parser needs no extension.
- Artifact
- io.heapy.kotmark:kotmark-ext-heading-anchor:0.1.0
- Package
- io.heapy.kotmark.ext.heading.anchor
Usage
Configure a prefix and a fallback ID for headings whose text has no slug characters.
Customize heading IDs
import io.heapy.kotmark.ext.heading.anchor.headingAnchor
import io.heapy.kotmark.extensions
import io.heapy.kotmark.parser.parser
import io.heapy.kotmark.renderer.html.htmlRenderer
fun renderWithHeadingIds(markdown: String): String {
val extensions = extensions {
headingAnchor {
idPrefix = "section-"
defaultId = "untitled"
}
}
// Heading IDs are an HTML attribute; the parser needs no extension.
val document = parser().parse(markdown)
return htmlRenderer { extensions(extensions) }.render(document)
}Example
INPUT · Markdown
# Getting started
## Getting started
#OUTPUT · HTML
<h1 id="section-getting-started">Getting started</h1>
<h2 id="section-getting-started-1">Getting started</h2>
<h1 id="section-untitled"></h1>ID generation
Heading text is normalized to lowercase, punctuation is removed, and repeated IDs get a numeric suffix. The extension can add a prefix and suffix to each generated value.
Generated IDs also avoid collisions with earlier suffixed headings: Header,
Header, Header-1 become header, header-1, header-1-1.
Combine this extension with table of contents to link an outline to the
same IDs.