gemtext-links.gmi (2533B)
1 {{- $references := .references -}} 2 {{- $titles := dict -}} 3 {{- range .page.Params.references -}} 4 {{- $titles = merge $titles (dict .url .title) -}} 5 {{- end -}} 6 {{- $linkPattern := `\[([^\]]+)\](?:\[(\d+)\]|\(([^)\n]+)\))` -}} 7 {{- $output := slice -}} 8 {{- $links := slice -}} 9 {{- $seen := dict -}} 10 {{- $preformatted := false -}} 11 {{- /* The final blank line flushes links from a paragraph at EOF. */ -}} 12 {{- range split (printf "%s\n" .content) "\n" -}} 13 {{- $line := . -}} 14 {{- $fence := hasPrefix $line "```" -}} 15 {{- if and (not $preformatted) (findRE `^\[\d+\]:[ \t]+` $line) -}} 16 {{- $line = "" -}} 17 {{- end -}} 18 {{- if and (not $preformatted) (or (eq (strings.TrimSpace $line) "") $fence (hasPrefix $line "=>")) -}} 19 {{- with $links -}} 20 {{- $output = $output | append "" -}} 21 {{- range . -}} 22 {{- $output = $output | append . -}} 23 {{- end -}} 24 {{- end -}} 25 {{- $links = slice -}} 26 {{- $seen = dict -}} 27 {{- end -}} 28 {{- if and (not $preformatted) (not $fence) (not (hasPrefix $line "=>")) -}} 29 {{- range findRE $linkPattern $line -}} 30 {{- $text := replaceRE $linkPattern `$1` . -}} 31 {{- $refNum := replaceRE $linkPattern `$2` . -}} 32 {{- $url := replaceRE $linkPattern `$3` . -}} 33 {{- with $refNum -}} 34 {{- $url = index $references . -}} 35 {{- end -}} 36 {{- with $url -}} 37 {{- $label := (index $titles . | default $text) | replaceRE `^[_*]+|[_*]+$` "" -}} 38 {{- if eq $text "via" -}} 39 {{- $label = printf "via %s" ((urls.Parse .).Host | default .) -}} 40 {{- end -}} 41 {{- if not (index $seen .) -}} 42 {{- $links = $links | append (printf "=> %s %s" . $label) -}} 43 {{- $seen = merge $seen (dict . true) -}} 44 {{- end -}} 45 {{- end -}} 46 {{- if $url -}} 47 {{- if eq $text "via" -}} 48 {{- /* Attribution lives on its link line, not as a dangling '(via)'. */ -}} 49 {{- $line = replace $line (printf " (%s)" .) "" -}} 50 {{- end -}} 51 {{- $line = replace $line . $text -}} 52 {{- end -}} 53 {{- end -}} 54 {{- end -}} 55 {{- $output = $output | append $line -}} 56 {{- if $fence -}} 57 {{- $preformatted = not $preformatted -}} 58 {{- end -}} 59 {{- end -}} 60 {{- return (delimit $output "\n") -}}