summaryrefslogtreecommitdiff
path: root/text.go
diff options
context:
space:
mode:
authorNicolas Sterchele <nicolas@sterchelen.net>2022-08-31 23:08:52 +0200
committerNicolas Sterchele <nicolas@sterchelen.net>2022-08-31 23:19:58 +0200
commitb9281c89737419216b710a87c31686d21adf86bc (patch)
treebc2b2c73b35ead61bee37b75aec1eee2d78c6ef4 /text.go
initial commit
Thanks to Ted Unangst for its work. Originally available here https://humungus.tedunangst.com/r/inks
Diffstat (limited to 'text.go')
-rwxr-xr-xtext.go80
1 files changed, 80 insertions, 0 deletions
diff --git a/text.go b/text.go
new file mode 100755
index 0000000..41e4219
--- /dev/null
+++ b/text.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "fmt"
+ "html"
+ "html/template"
+ "regexp"
+ "strings"
+)
+
+func htmlify(s string) template.HTML {
+ s = strings.Replace(s, "\r", "", -1)
+ s = prettyquotes(s)
+ s = html.EscapeString(s)
+
+ linkfn := func(url string) string {
+ addparen := false
+ adddot := false
+ if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
+ url = url[:len(url)-1]
+ addparen = true
+ }
+ if strings.HasSuffix(url, ".") {
+ url = url[:len(url)-1]
+ adddot = true
+ }
+ url = fmt.Sprintf(`<a href="%s">%s</a>`, url, url)
+ if adddot {
+ url += "."
+ }
+ if addparen {
+ url += ")"
+ }
+ return url
+ }
+ re_link := regexp.MustCompile(`https?://[^\s"]+[\w/)]`)
+ s = re_link.ReplaceAllStringFunc(s, linkfn)
+
+ re_i := regexp.MustCompile("&gt; (.*)\n?")
+ s = re_i.ReplaceAllString(s, "<blockquote>$1</blockquote>\n")
+ s = strings.Replace(s, "</blockquote>\n<blockquote>", "\n", -1)
+ s = strings.TrimSpace(s)
+ renl := regexp.MustCompile("\n+")
+ nlrepl := func(s string) string {
+ if len(s) > 1 {
+ return "\n<p>"
+ }
+ return "<br>\n"
+ }
+ s = renl.ReplaceAllStringFunc(s, nlrepl)
+
+ return template.HTML(s)
+}
+
+func prettyquotes(s string) string {
+ lq := "\u201c"
+ rq := "\u201d"
+ ls := "\u2018"
+ rs := "\u2019"
+ ap := rs
+ re_lq := regexp.MustCompile(`"[^.,\s]`)
+ lq_fn := func(s string) string {
+ return lq + s[1:]
+ }
+ s = re_lq.ReplaceAllStringFunc(s, lq_fn)
+ s = strings.Replace(s, `"`, rq, -1)
+ re_ap := regexp.MustCompile(`\w'`)
+ ap_fn := func(s string) string {
+ return s[0:len(s)-1] + ap
+ }
+ s = re_ap.ReplaceAllStringFunc(s, ap_fn)
+ re_ls := regexp.MustCompile(`'\w`)
+ ls_fn := func(s string) string {
+ return ls + s[1:]
+ }
+ s = re_ls.ReplaceAllStringFunc(s, ls_fn)
+ s = strings.Replace(s, `'`, rs, -1)
+
+ return s
+}