2020-09-29 02:59:04 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2020-09-29 14:57:15 +00:00
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"html"
|
2020-09-29 02:59:04 +00:00
|
|
|
"io"
|
2020-09-29 14:57:15 +00:00
|
|
|
|
|
|
|
"git.sr.ht/~adnano/gmi"
|
2020-09-29 02:59:04 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// GeminiToHTML reads Gemini from the provided reader and returns an HTML string.
|
2020-09-29 14:57:15 +00:00
|
|
|
func GeminiToHTML(r io.Reader) []byte {
|
|
|
|
var b bytes.Buffer
|
|
|
|
var pre bool
|
|
|
|
var list bool
|
2020-09-29 02:59:04 +00:00
|
|
|
|
2020-09-29 14:57:15 +00:00
|
|
|
b.WriteString("<link rel='stylesheet' href='/style.css'>\n")
|
2020-09-29 02:59:04 +00:00
|
|
|
|
2020-09-29 14:57:15 +00:00
|
|
|
text := gmi.Parse(r)
|
|
|
|
for _, l := range text {
|
|
|
|
if _, ok := l.(gmi.LineListItem); ok {
|
|
|
|
if !list {
|
|
|
|
list = true
|
|
|
|
b.WriteString("<ul>\n")
|
|
|
|
}
|
|
|
|
} else if list {
|
|
|
|
list = false
|
|
|
|
b.WriteString("</ul>\n")
|
2020-09-29 02:59:04 +00:00
|
|
|
}
|
|
|
|
|
2020-09-29 14:57:15 +00:00
|
|
|
switch l.(type) {
|
|
|
|
case gmi.LineLink:
|
|
|
|
link := l.(gmi.LineLink)
|
|
|
|
url := html.EscapeString(link.URL)
|
|
|
|
name := html.EscapeString(link.Name)
|
|
|
|
if name == "" {
|
|
|
|
name = url
|
2020-09-29 02:59:04 +00:00
|
|
|
}
|
2020-09-29 14:57:15 +00:00
|
|
|
fmt.Fprintf(&b, "<p><a href='%s'>%s</a></p>", url, name)
|
|
|
|
case gmi.LinePreformattingToggle:
|
|
|
|
pre = !pre
|
|
|
|
if pre {
|
|
|
|
b.WriteString("<pre>\n")
|
|
|
|
} else {
|
|
|
|
b.WriteString("</pre>\n")
|
2020-09-29 02:59:04 +00:00
|
|
|
}
|
2020-09-29 14:57:15 +00:00
|
|
|
case gmi.LinePreformattedText:
|
|
|
|
text := string(l.(gmi.LinePreformattedText))
|
|
|
|
fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
|
|
|
|
case gmi.LineHeading1:
|
|
|
|
text := string(l.(gmi.LineHeading1))
|
|
|
|
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
|
|
|
|
case gmi.LineHeading2:
|
|
|
|
text := string(l.(gmi.LineHeading2))
|
|
|
|
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
|
|
|
|
case gmi.LineHeading3:
|
|
|
|
text := string(l.(gmi.LineHeading3))
|
|
|
|
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
|
|
|
|
case gmi.LineListItem:
|
|
|
|
text := string(l.(gmi.LineListItem))
|
|
|
|
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
|
|
|
|
case gmi.LineQuote:
|
|
|
|
text := string(l.(gmi.LineQuote))
|
|
|
|
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
|
|
|
|
case gmi.LineText:
|
|
|
|
text := string(l.(gmi.LineText))
|
|
|
|
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text))
|
2020-09-29 02:59:04 +00:00
|
|
|
}
|
|
|
|
}
|
2020-09-29 14:57:15 +00:00
|
|
|
return b.Bytes()
|
2020-09-29 02:59:04 +00:00
|
|
|
}
|