gmi2html.go (view raw)
1package main
2
3import (
4 "fmt"
5 "html"
6 "strings"
7
8 "git.sr.ht/~adnano/go-gemini"
9)
10
11func textToHTML(text gemini.Text) string {
12 var b strings.Builder
13 var pre bool
14 var list bool
15 for _, l := range text {
16 if _, ok := l.(gemini.LineListItem); ok {
17 if !list {
18 list = true
19 fmt.Fprint(&b, "<ul>\n")
20 }
21 } else if list {
22 list = false
23 fmt.Fprint(&b, "</ul>\n")
24 }
25 switch l.(type) {
26 case gemini.LineLink:
27 link := l.(gemini.LineLink)
28 url := html.EscapeString(link.URL)
29 name := html.EscapeString(link.Name)
30 if name == "" {
31 name = url
32 }
33 fmt.Fprintf(&b, "<p><a href='%s'>%s</a></p>\n", url, name)
34 case gemini.LinePreformattingToggle:
35 pre = !pre
36 if pre {
37 altText := string(l.(gemini.LinePreformattingToggle))
38 if altText != "" {
39 altText = html.EscapeString(altText)
40 fmt.Fprintf(&b, "<pre title='%s'>\n", altText)
41 }
42 fmt.Fprint(&b, "<pre>\n")
43 } else {
44 fmt.Fprint(&b, "</pre>\n")
45 }
46 case gemini.LinePreformattedText:
47 text := string(l.(gemini.LinePreformattedText))
48 fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
49 case gemini.LineHeading1:
50 text := string(l.(gemini.LineHeading1))
51 fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
52 case gemini.LineHeading2:
53 text := string(l.(gemini.LineHeading2))
54 fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
55 case gemini.LineHeading3:
56 text := string(l.(gemini.LineHeading3))
57 fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
58 case gemini.LineListItem:
59 text := string(l.(gemini.LineListItem))
60 fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
61 case gemini.LineQuote:
62 text := string(l.(gemini.LineQuote))
63 fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
64 case gemini.LineText:
65 text := string(l.(gemini.LineText))
66 if text == "" {
67 fmt.Fprint(&b, "<br>\n")
68 } else {
69 fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text))
70 }
71 }
72 }
73 if pre {
74 fmt.Fprint(&b, "</pre>\n")
75 }
76 if list {
77 fmt.Fprint(&b, "</ul>\n")
78 }
79 return b.String()
80}