Skip to content

Commit 5f755e4

Browse files
authored
Encode link URIs before rendering into Gemtext
This makes gmnhg encode link destinations before rendering them into Gemtext according to RFC 3986. This particularly fixes spaces in links. Invalid URIs will skipped from rendering entirely. Fixes #49.
1 parent 62d762a commit 5f755e4

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

internal/renderer/link.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package renderer
1818
import (
1919
"fmt"
2020
"io"
21+
"net/url"
2122

2223
"github.com/gomarkdown/markdown/ast"
2324
)
@@ -27,8 +28,13 @@ func (r Renderer) link(w io.Writer, node *ast.Link, entering bool) {
2728
if node.Footnote != nil {
2829
fmt.Fprintf(w, "[^%d]: %s", node.NoteID, extractText(node.Footnote))
2930
} else {
31+
uri, err := url.Parse(string(node.Destination))
32+
if err != nil {
33+
// TODO: should we skip links with invalid URIs?
34+
return
35+
}
3036
w.Write(linkPrefix)
31-
w.Write(node.Destination)
37+
w.Write([]byte(uri.String()))
3238
w.Write(space)
3339
r.text(w, node, true)
3440
}

testdata/links.gmi

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ Other container elements can contain inline links as well. For instance, this is
2626

2727
=> https://xmpp.org/extensions/xep-0384.html XEP-0384
2828

29+
Links will get encoded according to RFC 3986, like this sample link to nowhere. The other sample link to somewhere on GitHub will not get transformed: sample.
30+
31+
=> /URI%20with%20spaces link
32+
=> https://github.com:443/request+with+characters%20 sample
33+
2934
## Footnotes
3035

3136
gmnhg supports footnotes, written like this[^1]. Footnotes can use any references, including alphanumeric ones[^2]; alphanumeric references will be replaced with numeric IDs on render.

testdata/links.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@ this is an example of a link inside a blockquote:
3232
> OTR has significant usability drawbacks for inter-client mobility.
3333
> [XEP-0384](https://xmpp.org/extensions/xep-0384.html)
3434
35+
Links will get encoded according to RFC 3986, like this sample
36+
[link](/URI with spaces) to nowhere. The other sample link to
37+
somewhere on GitHub will not get transformed: [sample][elsewhere].
38+
39+
[elsewhere]: https://github.com:443/request+with+characters%20
40+
3541
## Footnotes
3642

3743
gmnhg supports footnotes, written like this[^1]. Footnotes can use any

0 commit comments

Comments
 (0)