all repos — honk @ 9e0c9b01fa61e22fdbf0c82f2808cfa9c50d54df

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?`)
 37var re_tabler = regexp.MustCompile(`((^|\n)\|.*)+\n?`)
 38var re_header = regexp.MustCompile(`(^|\n)(#+) (.*)`)
 39
 40var lighter = synlight.New(synlight.Options{Format: synlight.HTML})
 41
 42func markitzero(s string) string {
 43	// prepare the string
 44	s = strings.TrimSpace(s)
 45	s = strings.Replace(s, "\r", "", -1)
 46
 47	codeword := "`elided big code`"
 48
 49	// save away the code blocks so we don't mess them up further
 50	var bigcodes, lilcodes, images []string
 51	s = re_bigcoder.ReplaceAllStringFunc(s, func(code string) string {
 52		bigcodes = append(bigcodes, code)
 53		return codeword
 54	})
 55	s = re_coder.ReplaceAllStringFunc(s, func(code string) string {
 56		lilcodes = append(lilcodes, code)
 57		return "`x`"
 58	})
 59	s = re_imgfix.ReplaceAllStringFunc(s, func(img string) string {
 60		images = append(images, img)
 61		return "<img x>"
 62	})
 63
 64	// fewer side effects than html.EscapeString
 65	buf := make([]byte, 0, len(s))
 66	for _, c := range []byte(s) {
 67		switch c {
 68		case '&':
 69			buf = append(buf, []byte("&amp;")...)
 70		case '<':
 71			buf = append(buf, []byte("&lt;")...)
 72		case '>':
 73			buf = append(buf, []byte("&gt;")...)
 74		default:
 75			buf = append(buf, c)
 76		}
 77	}
 78	s = string(buf)
 79
 80	// mark it zero
 81	if strings.Contains(s, "http") {
 82		s = re_link.ReplaceAllStringFunc(s, linkreplacer)
 83	}
 84	s = re_zerolink.ReplaceAllString(s, `<a href="$2">$1</a>`)
 85	if strings.Contains(s, "*") {
 86		s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
 87		s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
 88	}
 89	s = re_quoter.ReplaceAllString(s, "<blockquote>$1<br><cite>$3</cite></blockquote><p>")
 90	s = re_reciter.ReplaceAllString(s, "$1$2$3")
 91	s = strings.Replace(s, "\n---\n", "<hr><p>", -1)
 92
 93	s = re_lister.ReplaceAllStringFunc(s, func(m string) string {
 94		m = strings.Trim(m, "\n")
 95		items := strings.Split(m, "\n")
 96		r := "<ul>"
 97		for _, item := range items {
 98			r += "<li>" + strings.Trim(item[1:], " ")
 99		}
100		r += "</ul><p>"
101		return r
102	})
103	s = re_tabler.ReplaceAllStringFunc(s, func(m string) string {
104		m = strings.Trim(m, "\n")
105		rows := strings.Split(m, "\n")
106		var r strings.Builder
107		r.WriteString("<table>")
108		alignments := make(map[int]string)
109		for _, row := range rows {
110			hastr := false
111			cells := strings.Split(row, "|")
112			for i, cell := range cells {
113				cell = strings.TrimSpace(cell)
114				if cell == "" && (i == 0 || i == len(cells)-1) {
115					continue
116				}
117				switch cell {
118				case ":---":
119					alignments[i] = ` style="text-align: left"`
120					continue
121				case ":---:":
122					alignments[i] = ` style="text-align: center"`
123					continue
124				case "---:":
125					alignments[i] = ` style="text-align: right"`
126					continue
127				}
128				if !hastr {
129					r.WriteString("<tr>")
130					hastr = true
131				}
132				fmt.Fprintf(&r, "<td%s>", alignments[i])
133				r.WriteString(cell)
134			}
135		}
136		r.WriteString("</table><p>")
137		return r.String()
138	})
139	s = re_header.ReplaceAllStringFunc(s, func(s string) string {
140		m := re_header.FindStringSubmatch(s)
141		num := len(m[2])
142		return fmt.Sprintf("<h%d>%s</h%d><p>", num, m[3], num)
143	})
144
145	// restore images
146	s = strings.Replace(s, "&lt;img x&gt;", "<img x>", -1)
147	s = re_imgfix.ReplaceAllStringFunc(s, func(string) string {
148		img := images[0]
149		images = images[1:]
150		return img
151	})
152
153	// now restore the code blocks
154	s = re_coder.ReplaceAllStringFunc(s, func(string) string {
155		code := lilcodes[0]
156		lilcodes = lilcodes[1:]
157		if code == codeword && len(bigcodes) > 0 {
158			code := bigcodes[0]
159			bigcodes = bigcodes[1:]
160			m := re_bigcoder.FindStringSubmatch(code)
161			return "<pre><code>" + lighter.HighlightString(m[2], m[1]) + "</code></pre><p>"
162		}
163		code = html.EscapeString(code)
164		return code
165	})
166
167	s = re_coder.ReplaceAllString(s, "<code>$1</code>")
168
169	// some final fixups
170	s = strings.Replace(s, "\n", "<br>", -1)
171	s = strings.Replace(s, "<br><blockquote>", "<blockquote>", -1)
172	s = strings.Replace(s, "<br><cite></cite>", "", -1)
173	s = strings.Replace(s, "<br><pre>", "<pre>", -1)
174	s = strings.Replace(s, "<br><ul>", "<ul>", -1)
175	s = strings.Replace(s, "<br><table>", "<table>", -1)
176	s = strings.Replace(s, "<p><br>", "<p>", -1)
177	return s
178}
179
180func linkreplacer(url string) string {
181	if url[0:2] == "](" {
182		return url
183	}
184	prefix := ""
185	for !strings.HasPrefix(url, "http") {
186		prefix += url[0:1]
187		url = url[1:]
188	}
189	addparen := false
190	adddot := false
191	if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
192		url = url[:len(url)-1]
193		addparen = true
194	}
195	if strings.HasSuffix(url, ".") {
196		url = url[:len(url)-1]
197		adddot = true
198	}
199	url = fmt.Sprintf(`<a href="%s">%s</a>`, url, url)
200	if adddot {
201		url += "."
202	}
203	if addparen {
204		url += ")"
205	}
206	return prefix + url
207}