forked from PaulSonOfLars/gotg_md2html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmd2htmlV2.go
271 lines (232 loc) · 6.85 KB
/
md2htmlV2.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
package main
import (
"html"
"sort"
"strings"
)
var defaultConverterV2 = ConverterV2{
Prefixes: map[string]string{
"url": "buttonurl:",
},
SameLineSuffix: sameLineSuffix,
}
// ButtonV2 identifies a button. It can contain either a URL, or Text, depending on whether it is a buttonURL: or a buttonText:
type ButtonV2 struct {
Name string
Type string
Content string
SameLine bool
}
type ConverterV2 struct {
Prefixes map[string]string
SameLineSuffix string
}
func NewV2(prefixes map[string]string) *ConverterV2 {
return &ConverterV2{
Prefixes: prefixes,
SameLineSuffix: sameLineSuffix,
}
}
func MD2HTMLV2(in string) string {
return defaultConverterV2.MD2HTML(in)
}
func MD2HTMLButtonsV2(in string) (string, []ButtonV2) {
return defaultConverterV2.MD2HTMLButtons(in)
}
var chars = map[string]string{
"`": "code",
"```": "pre",
"_": "i",
"*": "b",
"~": "s",
"__": "u",
"|": "", // this is a placeholder for || to work
"||": "span class=\"tg-spoiler\"",
"!": "", // for emoji
"[": "", // for links
"]": "", // for links/emoji
"(": "", // for links/emoji
")": "", // for links/emoji
"\\": "", // for escapes
}
var AllMarkdownV2Chars = func() []rune {
var outString []string
for k := range chars {
outString = append(outString, k)
}
sort.Strings(outString)
var out []rune
for _, x := range outString {
out = append(out, []rune(x)[0])
}
return out
}()
func (cv ConverterV2) MD2HTML(in string) string {
text, _ := cv.md2html([]rune(html.EscapeString(in)), false)
return strings.TrimSpace(text)
}
func (cv ConverterV2) MD2HTMLButtons(in string) (string, []ButtonV2) {
text, btns := cv.md2html([]rune(html.EscapeString(in)), true)
return strings.TrimSpace(text), btns
}
var skipStarts = map[rune]bool{
'!': true, // premium emoji
'[': true, // links
}
// TODO: add support for a map-like check of which items cannot be included.
//
// Eg: `code` cannot be italic/bold/underline/strikethrough
// however... this is currently implemented by server side by telegram, so not my problem :runs:
//
// (see notes on: https://core.telegram.org/bots/api#markdownv2-style)
func (cv ConverterV2) md2html(in []rune, enableButtons bool) (string, []ButtonV2) {
out := strings.Builder{}
for i := 0; i < len(in); i++ {
c := in[i]
if _, ok := chars[string(c)]; !ok {
out.WriteRune(c)
continue
}
if !validStart(i, in) && !skipStarts[c] {
if c == '\\' && i+1 < len(in) {
if _, ok := chars[string(in[i+1])]; ok {
out.WriteRune(in[i+1])
i++
continue
}
}
out.WriteRune(c)
continue
}
switch c {
case '`', '*', '~', '_', '|': // '||', '__', and '```' are included here too
item := string(c)
if c == '|' { // support ||
// if single |, ignore. We only care about double ||
if i+1 >= len(in) || in[i+1] != '|' {
out.WriteRune(c)
continue
}
item = "||"
i++
} else if c == '_' && i+1 < len(in) && in[i+1] == '_' { // support __
item = "__"
i++
} else if c == '`' && i+2 < len(in) && in[i+1] == '`' && in[i+2] == '`' { // support ```
item = "```"
i += 2
}
if i+1 >= len(in) {
out.WriteString(item)
continue
}
idx := getValidEnd(in[i+1:], item)
if idx < 0 {
// not found; write and move on.
out.WriteString(item)
continue
}
nStart, nEnd := i+1, i+idx+1
followT, followB := cv.md2html(in[nEnd+len(item):], enableButtons)
if item == "`" {
// ` doesn't support nested items, so don't parse children.
return out.String() + "<code>" + string(in[nStart:nEnd]) + "</code>" + followT, followB
} else if item == "```" {
// ``` doesn't support nested items, so don't parse children.
nestedT := string(in[nStart:nEnd])
// Attempt to extract language details; should only be first line
splitLines := strings.Split(nestedT, "\n")
if len(splitLines) > 1 {
// TODO: How do we decide the language; first word? first line?
firstLine := strings.TrimSpace(splitLines[0])
if len(firstLine) > 0 && strings.HasPrefix(nestedT, firstLine) {
content := strings.TrimPrefix(nestedT, firstLine+"\n")
return out.String() + "<pre><code class=\"language-" + firstLine + "\">" + content + "</code></pre>" + followT, followB
}
}
return out.String() + "<pre>" + strings.TrimPrefix(nestedT, "\n") + "</pre>" + followT, followB
}
// internal won't have any interesting item closings
nestedT, nestedB := cv.md2html(in[nStart:nEnd], enableButtons)
return out.String() + "<" + chars[item] + ">" + nestedT + "</" + closeSpans(chars[item]) + ">" + followT, append(nestedB, followB...)
case '!':
if len(in) <= i+1 || in[i+1] != '[' {
out.WriteRune(c)
continue
}
ok, text, content, newEnd := getLinkContents(in[i+1:], true)
if !ok {
out.WriteRune(c)
continue
}
end := i + 1 + newEnd
content = strings.TrimPrefix(content, "tg://emoji?id=")
nestedT, nestedB := cv.md2html(text, enableButtons)
followT, followB := cv.md2html(in[end:], enableButtons)
return out.String() + `<tg-emoji emoji-id="` + content + `">` + nestedT + "</tg-emoji>" + followT, append(nestedB, followB...)
case '[':
ok, text, content, newEnd := getLinkContents(in[i:], false)
if !ok {
out.WriteRune(c)
continue
}
end := i + newEnd
followT, followB := cv.md2html(in[end:], enableButtons)
if enableButtons {
for buttonType, prefix := range cv.Prefixes {
if !strings.HasPrefix(content, prefix) {
continue
}
content := strings.TrimLeft(strings.TrimPrefix(content, prefix), "/")
sameline := strings.HasSuffix(content, cv.SameLineSuffix)
if sameline {
content = strings.TrimSuffix(content, cv.SameLineSuffix)
}
cleanedName := cv.StripMDV2(string(text))
return out.String() + followT, append([]ButtonV2{{
Name: html.UnescapeString(cleanedName),
Type: buttonType,
Content: content,
SameLine: sameline,
}}, followB...)
}
}
nestedT, nestedB := cv.md2html(text, enableButtons)
return out.String() + `<a href="` + content + `">` + nestedT + "</a>" + followT, append(nestedB, followB...)
case ']', '(', ')':
out.WriteRune(c)
case '\\':
if i+1 < len(in) {
if _, ok := chars[string(in[i+1])]; ok {
out.WriteRune(in[i+1])
i++
continue
}
}
out.WriteRune(c)
}
}
return out.String(), nil
}
func EscapeMarkdownV2(r []rune) string {
out := strings.Builder{}
for i, x := range r {
if contains(x, AllMarkdownV2Chars) {
if i == 0 || i == len(r)-1 || validEnd(i, r) || validStart(i, r) {
out.WriteRune('\\')
}
}
out.WriteRune(x)
}
return out.String()
}
// closeSpans gets the correct closing tags for spans.
// eg:
// - closeSpans("span class=\"tg-spoiler\"") should return just "span"
// - closeSpans("pre") -> returns "pre"
func closeSpans(s string) string {
if !strings.HasPrefix(s, "span") {
return s
}
return "span"
}