html: Improve link abbreviation (#+LINK) resolution

Handle `%s`/`%h` interpolation and add support for shorthand of prefix only
links / links with empty tag (i.e. `[example]` instead of [example:]). See
[1] and [2]. As so often we don't match org mode output completely but our
output looks sane enough to me so let's move along for now.

[1] https://orgmode.org/manual/Link-Abbreviations.html
[2] https://github.com/bzg/org-mode/blob/main/lisp/ol.el#L1011
This commit is contained in:
Niklas Fasching 2021-10-25 16:47:26 +02:00
parent 34dfe32024
commit 9995b3cdad
5 changed files with 37 additions and 5 deletions

View file

@ -10,6 +10,8 @@ import (
"strings"
"unicode"
u "net/url"
h "golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
@ -361,7 +363,13 @@ func (w *HTMLWriter) WriteRegularLink(l RegularLink) {
url = strings.TrimSuffix(url, ".org") + ".html"
}
if prefix := w.document.Links[l.Protocol]; prefix != "" {
url = html.EscapeString(prefix) + strings.TrimPrefix(url, l.Protocol+":")
if tag := strings.TrimPrefix(l.URL, l.Protocol+":"); strings.Contains(prefix, "%s") || strings.Contains(prefix, "%h") {
url = html.EscapeString(strings.ReplaceAll(strings.ReplaceAll(prefix, "%s", tag), "%h", u.QueryEscape(tag)))
} else {
url = html.EscapeString(prefix) + tag
}
} else if prefix := w.document.Links[l.URL]; prefix != "" {
url = html.EscapeString(strings.ReplaceAll(strings.ReplaceAll(prefix, "%s", ""), "%h", ""))
}
switch l.Kind() {
case "image":