summaryrefslogtreecommitdiffstats
path: root/internal/cms/markdown.go
blob: 49149b8e7e809038958a6152b3f45445e305146c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package cms

import (
	"regexp"
	"strings"
)

var (
	standaloneMarkdownLink = regexp.MustCompile(`^\s*\[([^\]]+)\]\(([^)]+)\)\s*$`)
	inlineMarkdownLink     = regexp.MustCompile(`\[([^\]]+)\]\(([^)]+)\)`)
)

func markdownToGemtext(body string) string {
	var out []string
	inFence := false

	for _, line := range strings.Split(strings.ReplaceAll(body, "\r\n", "\n"), "\n") {
		trimmed := strings.TrimSpace(line)
		if strings.HasPrefix(trimmed, "```") {
			inFence = !inFence
			out = append(out, line)
			continue
		}
		if inFence {
			out = append(out, line)
			continue
		}
		if match := standaloneMarkdownLink.FindStringSubmatch(line); match != nil {
			out = append(out, "=> "+match[2]+" "+match[1])
			continue
		}
		if strings.HasPrefix(trimmed, "- ") {
			indent := line[:strings.Index(line, "-")]
			line = indent + "* " + strings.TrimPrefix(trimmed, "- ")
		}
		line = inlineMarkdownLink.ReplaceAllString(line, "$1 ($2)")
		line = strings.ReplaceAll(line, "**", "")
		line = strings.ReplaceAll(line, "__", "")
		out = append(out, line)
	}

	return strings.TrimRight(strings.Join(out, "\n"), "\n") + "\n"
}