From 5f755e4fa39b2dc60f85ac480e92faa9885193e4 Mon Sep 17 00:00:00 2001 From: Timur Demin Date: Fri, 14 Jan 2022 00:19:40 +0500 Subject: [PATCH] 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. --- internal/renderer/link.go | 8 +++++++- testdata/links.gmi | 5 +++++ testdata/links.md | 6 ++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/internal/renderer/link.go b/internal/renderer/link.go index 460a37e..27f4e2a 100644 --- a/internal/renderer/link.go +++ b/internal/renderer/link.go @@ -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) } diff --git a/testdata/links.gmi b/testdata/links.gmi index ceef428..6053281 100644 --- a/testdata/links.gmi +++ b/testdata/links.gmi @@ -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. diff --git a/testdata/links.md b/testdata/links.md index be307d7..a6219b2 100644 --- a/testdata/links.md +++ b/testdata/links.md @@ -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