diff options
| author | Nicolas Sterchele <nicolas@sterchelen.net> | 2022-08-31 23:08:52 +0200 |
|---|---|---|
| committer | Nicolas Sterchele <nicolas@sterchelen.net> | 2022-08-31 23:19:58 +0200 |
| commit | b9281c89737419216b710a87c31686d21adf86bc (patch) | |
| tree | bc2b2c73b35ead61bee37b75aec1eee2d78c6ef4 /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-x | text.go | 80 |
1 files changed, 80 insertions, 0 deletions
@@ -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("> (.*)\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 +} |
