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.
This commit is contained in:
Timur Demin 2022-01-14 00:19:40 +05:00 committed by GitHub
parent 62d762a8c7
commit 5f755e4fa3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 1 deletions

View file

@ -18,6 +18,7 @@ package renderer
import (
"fmt"
"io"
"net/url"
"github.com/gomarkdown/markdown/ast"
)
@ -27,8 +28,13 @@ func (r Renderer) link(w io.Writer, node *ast.Link, entering bool) {
if node.Footnote != nil {
fmt.Fprintf(w, "[^%d]: %s", node.NoteID, extractText(node.Footnote))
} else {
uri, err := url.Parse(string(node.Destination))
if err != nil {
// TODO: should we skip links with invalid URIs?
return
}
w.Write(linkPrefix)
w.Write(node.Destination)
w.Write([]byte(uri.String()))
w.Write(space)
r.text(w, node, true)
}

5
testdata/links.gmi vendored
View file

@ -26,6 +26,11 @@ Other container elements can contain inline links as well. For instance, this is
=> https://xmpp.org/extensions/xep-0384.html XEP-0384
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.
=> /URI%20with%20spaces link
=> https://github.com:443/request+with+characters%20 sample
## Footnotes
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.

6
testdata/links.md vendored
View file

@ -32,6 +32,12 @@ this is an example of a link inside a blockquote:
> OTR has significant usability drawbacks for inter-client mobility.
> — [XEP-0384](https://xmpp.org/extensions/xep-0384.html)
Links will get encoded according to RFC 3986, like this sample
[link](/URI with spaces) to nowhere. The other sample link to
somewhere on GitHub will not get transformed: [sample][elsewhere].
[elsewhere]: https://github.com:443/request+with+characters%20
## Footnotes
gmnhg supports footnotes, written like this[^1]. Footnotes can use any