all repos — honk @ 4a2eaddaf5dd2712c4a821c6b169d1f8fab27676

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