Extension 01 / kotmark-ext-autolink
Autolink
Autolinks are converted into ordinary link nodes, so the feature works with every renderer.
- Artifact
- io.heapy.kotmark:kotmark-ext-autolink:0.1.0
- Package
- io.heapy.kotmark.ext.autolink
Usage
Add the extension module and register it with the parser.
Detect links while parsing
import io.heapy.kotmark.ext.autolink.AutolinkType
import io.heapy.kotmark.ext.autolink.autolink
import io.heapy.kotmark.extensions
import io.heapy.kotmark.parser.parser
import io.heapy.kotmark.renderer.html.htmlRenderer
fun renderWithAutolinks(markdown: String): String {
val extensions = extensions {
autolink { linkTypes = setOf(AutolinkType.URL, AutolinkType.EMAIL) }
}
// Autolinks are found while parsing; the HTML renderer sees ordinary links.
val document = parser { extensions(extensions) }.parse(markdown)
return htmlRenderer().render(document)
}Example
INPUT · Markdown
Visit https://example.com or write to team@example.com.OUTPUT · HTML
<p>Visit <a href="https://example.com">https://example.com</a> or write to <a href="mailto:team@example.com">team@example.com</a>.</p>Behavior
- Code spans and code blocks are not scanned.
- Only lowercase
wwwis recognized. - The standalone
autolinkartifact also provides link extraction for plain text.
GFM differences
The extractor follows autolink-java rules. These differ from GFM in three examples from its Autolinks specification section:
| Example | Difference |
|---|---|
| 5 | An unmatched closing parenthesis stops the link even when more URL text follows. |
| 6 | &hl remains inside the link while its final semicolon stays outside. |
| 11 | An email prefix before a trailing - or _ is linked. |
Extract plain-text links
The standalone autolink module extracts spans without parsing Markdown.
Extract URL, www, and email spans
import io.heapy.kotmark.autolink.LinkType
import io.heapy.kotmark.autolink.linkExtractor
fun findLinks(text: String): List<String> {
val extractor = linkExtractor {
linkTypes = setOf(LinkType.URL, LinkType.WWW, LinkType.EMAIL)
}
return extractor.extractLinks(text).map { span ->
"${span.type}: ${text.substring(span.beginIndex, span.endIndex)}"
}
}INPUT · Plain text
See www.kotlinlang.org and https://example.com.OUTPUT · Link spans
WWW: www.kotlinlang.org
URL: https://example.com