all repos — honk @ 7ed3b24f1a2c7c1d9fed8486ebe3cdb7bf3edb41

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