all repos — honk @ a125322e4b7aff7e73c8051e22263f3b44b67516

my fork of honk

markitzero.go (view raw)

  1//
  2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
  3//
  4// Permission to use, copy, modify, and distribute this software for any
  5// purpose with or without fee is hereby granted, provided that the above
  6// copyright notice and this permission notice appear in all copies.
  7//
  8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 15
 16package main
 17
 18import (
 19	"fmt"
 20	"regexp"
 21	"strings"
 22
 23	"golang.org/x/net/html"
 24	"humungus.tedunangst.com/r/webs/synlight"
 25)
 26
 27var re_bolder = regexp.MustCompile(`(^|\W)\*\*((?s:.*?))\*\*($|\W)`)
 28var re_italicer = regexp.MustCompile(`(^|\W)\*((?s:.*?))\*($|\W)`)
 29var re_bigcoder = regexp.MustCompile("```(.*)\n?((?s:.*?))\n?```\n?")
 30var re_coder = regexp.MustCompile("`([^`]*)`")
 31var re_quoter = regexp.MustCompile(`(?m:^&gt; (.*)(\n- ?(.*))?\n?)`)
 32var re_reciter = regexp.MustCompile(`(<cite><a href=".*?">)https://twitter.com/([^/]+)/.*?(</a></cite>)`)
 33var re_link = regexp.MustCompile(`.?.?https?://[^\s"]+[\w/)!]`)
 34var re_zerolink = regexp.MustCompile(`\[([^]]*)\]\(([^)]*\)?)\)`)
 35var re_imgfix = regexp.MustCompile(`<img ([^>]*)>`)
 36var re_lister = regexp.MustCompile(`((^|\n)(\+|-).*)+\n?`)
 37
 38var lighter = synlight.New(synlight.Options{Format: synlight.HTML})
 39
 40func markitzero(s string) string {
 41	// prepare the string
 42	s = strings.TrimSpace(s)
 43	s = strings.Replace(s, "\r", "", -1)
 44
 45	// save away the code blocks so we don't mess them up further
 46	var bigcodes, lilcodes, images []string
 47	s = re_bigcoder.ReplaceAllStringFunc(s, func(code string) string {
 48		bigcodes = append(bigcodes, code)
 49		return "``````"
 50	})
 51	s = re_coder.ReplaceAllStringFunc(s, func(code string) string {
 52		lilcodes = append(lilcodes, code)
 53		return "`x`"
 54	})
 55	s = re_imgfix.ReplaceAllStringFunc(s, func(img string) string {
 56		images = append(images, img)
 57		return "<img x>"
 58	})
 59
 60	// fewer side effects than html.EscapeString
 61	buf := make([]byte, 0, len(s))
 62	for _, c := range []byte(s) {
 63		switch c {
 64		case '&':
 65			buf = append(buf, []byte("&amp;")...)
 66		case '<':
 67			buf = append(buf, []byte("&lt;")...)
 68		case '>':
 69			buf = append(buf, []byte("&gt;")...)
 70		default:
 71			buf = append(buf, c)
 72		}
 73	}
 74	s = string(buf)
 75
 76	// mark it zero
 77	s = re_link.ReplaceAllStringFunc(s, linkreplacer)
 78	s = re_zerolink.ReplaceAllString(s, `<a href="$2">$1</a>`)
 79	s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
 80	s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
 81	s = re_quoter.ReplaceAllString(s, "<blockquote>$1<br><cite>$3</cite></blockquote><p>")
 82	s = re_reciter.ReplaceAllString(s, "$1$2$3")
 83	s = strings.Replace(s, "\n---\n", "<hr><p>", -1)
 84
 85	s = re_lister.ReplaceAllStringFunc(s, func(m string) string {
 86		m = strings.Trim(m, "\n")
 87		items := strings.Split(m, "\n")
 88		r := "<ul>"
 89		for _, item := range items {
 90			r += "<li>" + strings.Trim(item[1:], " ")
 91		}
 92		r += "</ul><p>"
 93		return r
 94	})
 95
 96	// restore images
 97	s = strings.Replace(s, "&lt;img x&gt;", "<img x>", -1)
 98	s = re_imgfix.ReplaceAllStringFunc(s, func(string) string {
 99		img := images[0]
100		images = images[1:]
101		return img
102	})
103
104	// now restore the code blocks
105	s = re_coder.ReplaceAllStringFunc(s, func(string) string {
106		code := lilcodes[0]
107		lilcodes = lilcodes[1:]
108		code = html.EscapeString(code)
109		return code
110	})
111	s = re_bigcoder.ReplaceAllStringFunc(s, func(string) string {
112		code := bigcodes[0]
113		bigcodes = bigcodes[1:]
114		m := re_bigcoder.FindStringSubmatch(code)
115		return "<pre><code>" + lighter.HighlightString(m[2], m[1]) + "</code></pre><p>"
116	})
117	s = re_coder.ReplaceAllString(s, "<code>$1</code>")
118
119	// some final fixups
120	s = strings.Replace(s, "\n", "<br>", -1)
121	s = strings.Replace(s, "<br><blockquote>", "<blockquote>", -1)
122	s = strings.Replace(s, "<br><cite></cite>", "", -1)
123	s = strings.Replace(s, "<br><pre>", "<pre>", -1)
124	s = strings.Replace(s, "<br><ul>", "<ul>", -1)
125	s = strings.Replace(s, "<p><br>", "<p>", -1)
126	return s
127}
128
129func linkreplacer(url string) string {
130	if url[0:2] == "](" {
131		return url
132	}
133	prefix := ""
134	for !strings.HasPrefix(url, "http") {
135		prefix += url[0:1]
136		url = url[1:]
137	}
138	addparen := false
139	adddot := false
140	if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
141		url = url[:len(url)-1]
142		addparen = true
143	}
144	if strings.HasSuffix(url, ".") {
145		url = url[:len(url)-1]
146		adddot = true
147	}
148	url = fmt.Sprintf(`<a href="%s">%s</a>`, url, url)
149	if adddot {
150		url += "."
151	}
152	if addparen {
153		url += ")"
154	}
155	return prefix + url
156}