-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.go
304 lines (266 loc) · 8.21 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
Package github_flavored_markdown provides a GitHub Flavored Markdown renderer
with fenced code block highlighting, clickable header anchor links.
The functionality should be equivalent to the GitHub Markdown API endpoint specified at
https://developer.github.com/v3/markdown/#render-a-markdown-document-in-raw-mode, except
the rendering is performed locally.
See example below for how to generate a complete HTML page, including CSS styles.
*/
package github_flavored_markdown
import (
"bytes"
"fmt"
"html"
"io"
"regexp"
"sort"
"strings"
"text/template"
"unicode"
"github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday"
"github.com/shurcooL/go/u/u7"
"github.com/sourcegraph/annotate"
"github.com/sourcegraph/syntaxhighlight"
)
// Markdown renders GitHub Flavored Markdown text.
func Markdown(text []byte) []byte {
htmlFlags := 0
//htmlFlags |= blackfriday.HTML_SANITIZE_OUTPUT
htmlFlags |= blackfriday.HTML_GITHUB_BLOCKCODE
renderer := &renderer{Html: blackfriday.HtmlRenderer(htmlFlags, "", "").(*blackfriday.Html)}
// Parser extensions for GitHub Flavored Markdown.
extensions := 0
extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
extensions |= blackfriday.EXTENSION_TABLES
extensions |= blackfriday.EXTENSION_FENCED_CODE
extensions |= blackfriday.EXTENSION_AUTOLINK
extensions |= blackfriday.EXTENSION_STRIKETHROUGH
extensions |= blackfriday.EXTENSION_SPACE_HEADERS
//extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
unsanitized := blackfriday.Markdown(text, renderer, extensions)
// GitHub Flavored Markdown-like sanitization policy.
p := bluemonday.UGCPolicy()
p.AllowAttrs("class").Matching(bluemonday.SpaceSeparatedTokens).OnElements("div", "span")
p.AllowAttrs("class", "name").Matching(bluemonday.SpaceSeparatedTokens).OnElements("a")
p.AllowAttrs("rel").Matching(regexp.MustCompile(`^nofollow$`)).OnElements("a")
p.AllowAttrs("aria-hidden").Matching(regexp.MustCompile(`^true$`)).OnElements("a")
p.AllowDataURIImages()
return p.SanitizeBytes(unsanitized)
}
type renderer struct {
*blackfriday.Html
}
// GitHub Flavored Markdown header with clickable and hidden anchor.
func (_ *renderer) Header(out *bytes.Buffer, text func() bool, level int, _ string) {
marker := out.Len()
doubleSpace(out)
if !text() {
out.Truncate(marker)
return
}
textString := out.String()[marker:]
out.Truncate(marker)
anchorName := createSanitizedAnchorName(html.UnescapeString(textString))
out.WriteString(fmt.Sprintf(`<h%d><a name="%s" class="anchor" href="#%s" rel="nofollow" aria-hidden="true"><span class="octicon octicon-link"></span></a>`, level, anchorName, anchorName))
out.WriteString(textString)
out.WriteString(fmt.Sprintf("</h%d>\n", level))
}
// HeaderLink returns a relative link to the anchor of the given header.
func HeaderLink(header string) (link string) {
return "#" + createSanitizedAnchorName(header)
}
// Returns an anchor name for the given header text.
func createSanitizedAnchorName(text string) string {
var anchorName []rune
for _, r := range []rune(text) {
switch {
case r == ' ':
anchorName = append(anchorName, '-')
case unicode.IsLetter(r) || unicode.IsNumber(r):
anchorName = append(anchorName, unicode.ToLower(r))
}
}
return string(anchorName)
}
// TODO: Clean up and improve this code.
// GitHub Flavored Markdown fenced code block with highlighting.
func (_ *renderer) BlockCode(out *bytes.Buffer, text []byte, lang string) {
doubleSpace(out)
// parse out the language name
count := 0
for _, elt := range strings.Fields(lang) {
if elt[0] == '.' {
elt = elt[1:]
}
if len(elt) == 0 {
continue
}
out.WriteString(`<div class="highlight highlight-`)
attrEscape(out, []byte(elt))
lang = elt
out.WriteString(`"><pre>`)
count++
break
}
if count == 0 {
out.WriteString("<pre><code>")
}
if formattedCode, ok := formatCode(text, lang); ok {
out.Write(formattedCode)
} else {
attrEscape(out, text)
}
if count == 0 {
out.WriteString("</code></pre>\n")
} else {
out.WriteString("</pre></div>\n")
}
}
var gfmHtmlConfig = syntaxhighlight.HTMLConfig{
String: "s",
Keyword: "k",
Comment: "c",
Type: "n",
Literal: "lit",
Punctuation: "p",
Plaintext: "n",
Tag: "tag",
HTMLTag: "htm",
HTMLAttrName: "atn",
HTMLAttrValue: "atv",
Decimal: "m",
}
// TODO: Support highlighting for more languages.
func formatCode(src []byte, lang string) (formattedCode []byte, ok bool) {
switch lang {
// TODO: Use a highlighter based on go/scanner for Go code.
case "Go", "go":
var buf bytes.Buffer
err := syntaxhighlight.Print(syntaxhighlight.NewScanner(src), &buf, syntaxhighlight.HTMLPrinter(gfmHtmlConfig))
if err != nil {
return nil, false
}
return buf.Bytes(), true
case "diff":
switch 2 {
default:
var buf bytes.Buffer
err := u7.Print(u7.NewScanner(src), &buf)
if err != nil {
return nil, false
}
return buf.Bytes(), true
case 1:
lines := bytes.Split(src, []byte("\n"))
return bytes.Join(lines, []byte("\n")), true
case 2:
anns, err := u7.Annotate(src)
if err != nil {
return nil, false
}
lines := bytes.Split(src, []byte("\n"))
lineStarts := make([]int, len(lines))
var offset int
for lineIndex := 0; lineIndex < len(lines); lineIndex++ {
lineStarts[lineIndex] = offset
offset += len(lines[lineIndex]) + 1
}
lastDel, lastIns := -1, -1
for lineIndex := 0; lineIndex < len(lines); lineIndex++ {
var lineFirstChar byte
if len(lines[lineIndex]) > 0 {
lineFirstChar = lines[lineIndex][0]
}
switch lineFirstChar {
case '+':
if lastIns == -1 {
lastIns = lineIndex
}
case '-':
if lastDel == -1 {
lastDel = lineIndex
}
default:
if lastDel != -1 || lastIns != -1 {
if lastDel == -1 {
lastDel = lastIns
} else if lastIns == -1 {
lastIns = lineIndex
}
beginOffsetLeft := lineStarts[lastDel]
endOffsetLeft := lineStarts[lastIns]
beginOffsetRight := lineStarts[lastIns]
endOffsetRight := lineStarts[lineIndex]
anns = append(anns, &annotate.Annotation{Start: beginOffsetLeft, End: endOffsetLeft, Left: []byte(`<span class="gd input-block">`), Right: []byte(`</span>`), WantInner: 0})
anns = append(anns, &annotate.Annotation{Start: beginOffsetRight, End: endOffsetRight, Left: []byte(`<span class="gi input-block">`), Right: []byte(`</span>`), WantInner: 0})
if '@' != lineFirstChar {
//leftContent := string(src[beginOffsetLeft:endOffsetLeft])
//rightContent := string(src[beginOffsetRight:endOffsetRight])
// This is needed to filter out the "-" and "+" at the beginning of each line from being highlighted.
// TODO: Still not completely filtered out.
leftContent := ""
for line := lastDel; line < lastIns; line++ {
leftContent += "\x00" + string(lines[line][1:]) + "\n"
}
rightContent := ""
for line := lastIns; line < lineIndex; line++ {
rightContent += "\x00" + string(lines[line][1:]) + "\n"
}
var sectionSegments [2][]*annotate.Annotation
u7.HighlightedDiffFunc(leftContent, rightContent, §ionSegments, [2]int{beginOffsetLeft, beginOffsetRight})
anns = append(anns, sectionSegments[0]...)
anns = append(anns, sectionSegments[1]...)
}
}
lastDel, lastIns = -1, -1
}
}
sort.Sort(anns)
out, err := annotate.Annotate(src, anns, func(w io.Writer, b []byte) { template.HTMLEscape(w, b) })
if err != nil {
return nil, false
}
return out, true
}
default:
return nil, false
}
}
// Unexported blackfriday helpers.
func doubleSpace(out *bytes.Buffer) {
if out.Len() > 0 {
out.WriteByte('\n')
}
}
func escapeSingleChar(char byte) (string, bool) {
if char == '"' {
return """, true
}
if char == '&' {
return "&", true
}
if char == '<' {
return "<", true
}
if char == '>' {
return ">", true
}
return "", false
}
func attrEscape(out *bytes.Buffer, src []byte) {
org := 0
for i, ch := range src {
if entity, ok := escapeSingleChar(ch); ok {
if i > org {
// copy all the normal characters since the last escape
out.Write(src[org:i])
}
org = i + 1
out.WriteString(entity)
}
}
if org < len(src) {
out.Write(src[org:])
}
}