forked from niklasfasching/go-org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inline.go
416 lines (373 loc) · 12.9 KB
/
inline.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package org
import (
"fmt"
"path"
"regexp"
"strings"
"time"
"unicode"
)
type Text struct {
Content string
IsRaw bool
}
type LineBreak struct{ Count int }
type ExplicitLineBreak struct{}
type StatisticToken struct{ Content string }
type Timestamp struct {
Time time.Time
IsDate bool
Interval string
}
type Emphasis struct {
Kind string
Content []Node
}
type InlineBlock struct {
Name string
Parameters []string
Children []Node
}
type LatexFragment struct {
OpeningPair string
ClosingPair string
Content []Node
}
type FootnoteLink struct {
Name string
Definition *FootnoteDefinition
}
type RegularLink struct {
Protocol string
Description []Node
URL string
AutoLink bool
}
type Macro struct {
Name string
Parameters []string
}
var validURLCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;="
var autolinkProtocols = regexp.MustCompile(`^(https?|ftp|file)$`)
var imageExtensionRegexp = regexp.MustCompile(`^[.](png|gif|jpe?g|svg|tiff?)$`)
var videoExtensionRegexp = regexp.MustCompile(`^[.](webm|mp4)$`)
var subScriptSuperScriptRegexp = regexp.MustCompile(`^([_^]){([^{}]+?)}`)
var timestampRegexp = regexp.MustCompile(`^<(\d{4}-\d{2}-\d{2})( [A-Za-z]+)?( \d{2}:\d{2})?( \+\d+[dwmy])?>`)
var footnoteRegexp = regexp.MustCompile(`^\[fn:([\w-]*?)(:(.*?))?\]`)
var statisticsTokenRegexp = regexp.MustCompile(`^\[(\d+/\d+|\d+%)\]`)
var latexFragmentRegexp = regexp.MustCompile(`(?s)^\\begin{(\w+)}(.*)\\end{(\w+)}`)
var inlineBlockRegexp = regexp.MustCompile(`src_(\w+)(\[(.*)\])?{(.*)}`)
var inlineExportBlockRegexp = regexp.MustCompile(`@@(\w+):(.*?)@@`)
var macroRegexp = regexp.MustCompile(`{{{(.*)\((.*)\)}}}`)
var timestampFormat = "2006-01-02 Mon 15:04"
var datestampFormat = "2006-01-02 Mon"
var latexFragmentPairs = map[string]string{
`\(`: `\)`,
`\[`: `\]`,
`$$`: `$$`,
`$`: `$`,
}
func (d *Document) parseInline(input string) (nodes []Node) {
previous, current := 0, 0
for current < len(input) {
rewind, consumed, node := 0, 0, (Node)(nil)
switch input[current] {
case '^':
consumed, node = d.parseSubOrSuperScript(input, current)
case '_':
rewind, consumed, node = d.parseSubScriptOrEmphasisOrInlineBlock(input, current)
case '@':
consumed, node = d.parseInlineExportBlock(input, current)
case '*', '/', '+':
consumed, node = d.parseEmphasis(input, current, false)
case '=', '~':
consumed, node = d.parseEmphasis(input, current, true)
case '[':
consumed, node = d.parseOpeningBracket(input, current)
case '{':
consumed, node = d.parseMacro(input, current)
case '<':
consumed, node = d.parseTimestamp(input, current)
case '\\':
consumed, node = d.parseExplicitLineBreakOrLatexFragment(input, current)
case '$':
consumed, node = d.parseLatexFragment(input, current, 1)
case '\n':
consumed, node = d.parseLineBreak(input, current)
case ':':
rewind, consumed, node = d.parseAutoLink(input, current)
}
current -= rewind
if consumed != 0 {
if current > previous {
nodes = append(nodes, Text{input[previous:current], false})
}
if node != nil {
nodes = append(nodes, node)
}
current += consumed
previous = current
} else {
current++
}
}
if previous < len(input) {
nodes = append(nodes, Text{input[previous:], false})
}
return nodes
}
func (d *Document) parseRawInline(input string) (nodes []Node) {
previous, current := 0, 0
for current < len(input) {
if input[current] == '\n' {
consumed, node := d.parseLineBreak(input, current)
if current > previous {
nodes = append(nodes, Text{input[previous:current], true})
}
nodes = append(nodes, node)
current += consumed
previous = current
} else {
current++
}
}
if previous < len(input) {
nodes = append(nodes, Text{input[previous:], true})
}
return nodes
}
func (d *Document) parseLineBreak(input string, start int) (int, Node) {
i := start
for ; i < len(input) && input[i] == '\n'; i++ {
}
return i - start, LineBreak{i - start}
}
func (d *Document) parseInlineBlock(input string, start int) (int, int, Node) {
if !(strings.HasSuffix(input[:start], "src") && (start-4 < 0 || unicode.IsSpace(rune(input[start-4])))) {
return 0, 0, nil
}
if m := inlineBlockRegexp.FindStringSubmatch(input[start-3:]); m != nil {
return 3, len(m[0]), InlineBlock{"src", strings.Fields(m[1] + " " + m[3]), d.parseRawInline(m[4])}
}
return 0, 0, nil
}
func (d *Document) parseInlineExportBlock(input string, start int) (int, Node) {
if m := inlineExportBlockRegexp.FindStringSubmatch(input[start:]); m != nil {
return len(m[0]), InlineBlock{"export", m[1:2], d.parseRawInline(m[2])}
}
return 0, nil
}
func (d *Document) parseExplicitLineBreakOrLatexFragment(input string, start int) (int, Node) {
switch {
case start+2 >= len(input):
case input[start+1] == '\\' && start != 0 && input[start-1] != '\n':
for i := start + 2; i <= len(input)-1 && unicode.IsSpace(rune(input[i])); i++ {
if input[i] == '\n' {
return i + 1 - start, ExplicitLineBreak{}
}
}
case input[start+1] == '(' || input[start+1] == '[':
return d.parseLatexFragment(input, start, 2)
case strings.Index(input[start:], `\begin{`) == 0:
if m := latexFragmentRegexp.FindStringSubmatch(input[start:]); m != nil {
if open, content, close := m[1], m[2], m[3]; open == close {
openingPair, closingPair := `\begin{`+open+`}`, `\end{`+close+`}`
i := strings.Index(input[start:], closingPair)
return i + len(closingPair), LatexFragment{openingPair, closingPair, d.parseRawInline(content)}
}
}
}
return 0, nil
}
func (d *Document) parseLatexFragment(input string, start int, pairLength int) (int, Node) {
if start+2 >= len(input) {
return 0, nil
}
if pairLength == 1 && input[start:start+2] == "$$" {
pairLength = 2
}
openingPair := input[start : start+pairLength]
closingPair := latexFragmentPairs[openingPair]
if i := strings.Index(input[start+pairLength:], closingPair); i != -1 {
content := d.parseRawInline(input[start+pairLength : start+pairLength+i])
return i + pairLength + pairLength, LatexFragment{openingPair, closingPair, content}
}
return 0, nil
}
func (d *Document) parseSubOrSuperScript(input string, start int) (int, Node) {
if m := subScriptSuperScriptRegexp.FindStringSubmatch(input[start:]); m != nil {
return len(m[2]) + 3, Emphasis{m[1] + "{}", []Node{Text{m[2], false}}}
}
return 0, nil
}
func (d *Document) parseSubScriptOrEmphasisOrInlineBlock(input string, start int) (int, int, Node) {
if rewind, consumed, node := d.parseInlineBlock(input, start); consumed != 0 {
return rewind, consumed, node
} else if consumed, node := d.parseSubOrSuperScript(input, start); consumed != 0 {
return 0, consumed, node
}
consumed, node := d.parseEmphasis(input, start, false)
return 0, consumed, node
}
func (d *Document) parseOpeningBracket(input string, start int) (int, Node) {
if len(input[start:]) >= 2 && input[start] == '[' && input[start+1] == '[' {
return d.parseRegularLink(input, start)
} else if footnoteRegexp.MatchString(input[start:]) {
return d.parseFootnoteReference(input, start)
} else if statisticsTokenRegexp.MatchString(input[start:]) {
return d.parseStatisticToken(input, start)
}
return 0, nil
}
func (d *Document) parseMacro(input string, start int) (int, Node) {
if m := macroRegexp.FindStringSubmatch(input[start:]); m != nil {
return len(m[0]), Macro{m[1], strings.Split(m[2], ",")}
}
return 0, nil
}
func (d *Document) parseFootnoteReference(input string, start int) (int, Node) {
if m := footnoteRegexp.FindStringSubmatch(input[start:]); m != nil {
name, definition := m[1], m[3]
if name == "" && definition == "" {
return 0, nil
}
link := FootnoteLink{name, nil}
if definition != "" {
link.Definition = &FootnoteDefinition{name, []Node{Paragraph{d.parseInline(definition)}}, true}
}
return len(m[0]), link
}
return 0, nil
}
func (d *Document) parseStatisticToken(input string, start int) (int, Node) {
if m := statisticsTokenRegexp.FindStringSubmatch(input[start:]); m != nil {
return len(m[1]) + 2, StatisticToken{m[1]}
}
return 0, nil
}
func (d *Document) parseAutoLink(input string, start int) (int, int, Node) {
if !d.AutoLink || start == 0 || len(input[start:]) < 3 || input[start:start+3] != "://" {
return 0, 0, nil
}
protocolStart, protocol := start-1, ""
for ; protocolStart > 0; protocolStart-- {
if !unicode.IsLetter(rune(input[protocolStart])) {
protocolStart++
break
}
}
if m := autolinkProtocols.FindStringSubmatch(input[protocolStart:start]); m != nil {
protocol = m[1]
} else {
return 0, 0, nil
}
end := start
for ; end < len(input) && strings.ContainsRune(validURLCharacters, rune(input[end])); end++ {
}
path := input[start:end]
if path == "://" {
return 0, 0, nil
}
return len(protocol), len(path + protocol), RegularLink{protocol, nil, protocol + path, true}
}
func (d *Document) parseRegularLink(input string, start int) (int, Node) {
input = input[start:]
if len(input) < 3 || input[:2] != "[[" || input[2] == '[' {
return 0, nil
}
end := strings.Index(input, "]]")
if end == -1 {
return 0, nil
}
rawLinkParts := strings.Split(input[2:end], "][")
description, link := ([]Node)(nil), rawLinkParts[0]
if len(rawLinkParts) == 2 {
link, description = rawLinkParts[0], d.parseInline(rawLinkParts[1])
}
if strings.ContainsRune(link, '\n') {
return 0, nil
}
consumed := end + 2
protocol, linkParts := "", strings.SplitN(link, ":", 2)
if len(linkParts) == 2 {
protocol = linkParts[0]
}
return consumed, RegularLink{protocol, description, link, false}
}
func (d *Document) parseTimestamp(input string, start int) (int, Node) {
if m := timestampRegexp.FindStringSubmatch(input[start:]); m != nil {
ddmmyy, hhmm, interval, isDate := m[1], m[3], strings.TrimSpace(m[4]), false
if hhmm == "" {
hhmm, isDate = "00:00", true
}
t, err := time.Parse(timestampFormat, fmt.Sprintf("%s Mon %s", ddmmyy, hhmm))
if err != nil {
return 0, nil
}
timestamp := Timestamp{t, isDate, interval}
return len(m[0]), timestamp
}
return 0, nil
}
func (d *Document) parseEmphasis(input string, start int, isRaw bool) (int, Node) {
marker, i := input[start], start
if !hasValidPreAndBorderChars(input, i) {
return 0, nil
}
for i, consumedNewLines := i+1, 0; i < len(input) && consumedNewLines <= d.MaxEmphasisNewLines; i++ {
if input[i] == '\n' {
consumedNewLines++
}
if input[i] == marker && i != start+1 && hasValidPostAndBorderChars(input, i) {
if isRaw {
return i + 1 - start, Emphasis{input[start : start+1], d.parseRawInline(input[start+1 : i])}
}
return i + 1 - start, Emphasis{input[start : start+1], d.parseInline(input[start+1 : i])}
}
}
return 0, nil
}
// see org-emphasis-regexp-components (emacs elisp variable)
func hasValidPreAndBorderChars(input string, i int) bool {
return (i+1 >= len(input) || isValidBorderChar(rune(input[i+1]))) && (i == 0 || isValidPreChar(rune(input[i-1])))
}
func hasValidPostAndBorderChars(input string, i int) bool {
return (i == 0 || isValidBorderChar(rune(input[i-1]))) && (i+1 >= len(input) || isValidPostChar(rune(input[i+1])))
}
func isValidPreChar(r rune) bool {
return unicode.IsSpace(r) || strings.ContainsRune(`-({'"`, r)
}
func isValidPostChar(r rune) bool {
return unicode.IsSpace(r) || strings.ContainsRune(`-.,:!?;'")}[`, r)
}
func isValidBorderChar(r rune) bool { return !unicode.IsSpace(r) }
func (l RegularLink) Kind() string {
description := String(l.Description)
descProtocol, descExt := strings.SplitN(description, ":", 2)[0], path.Ext(description)
if ok := descProtocol == "file" || descProtocol == "http" || descProtocol == "https"; ok && imageExtensionRegexp.MatchString(descExt) {
return "image"
} else if ok && videoExtensionRegexp.MatchString(descExt) {
return "video"
}
if p := l.Protocol; l.Description != nil || (p != "" && p != "file" && p != "http" && p != "https") {
return "regular"
}
if imageExtensionRegexp.MatchString(path.Ext(l.URL)) {
return "image"
}
if videoExtensionRegexp.MatchString(path.Ext(l.URL)) {
return "video"
}
return "regular"
}
func (n Text) String() string { return orgWriter.WriteNodesAsString(n) }
func (n LineBreak) String() string { return orgWriter.WriteNodesAsString(n) }
func (n ExplicitLineBreak) String() string { return orgWriter.WriteNodesAsString(n) }
func (n StatisticToken) String() string { return orgWriter.WriteNodesAsString(n) }
func (n Emphasis) String() string { return orgWriter.WriteNodesAsString(n) }
func (n InlineBlock) String() string { return orgWriter.WriteNodesAsString(n) }
func (n LatexFragment) String() string { return orgWriter.WriteNodesAsString(n) }
func (n FootnoteLink) String() string { return orgWriter.WriteNodesAsString(n) }
func (n RegularLink) String() string { return orgWriter.WriteNodesAsString(n) }
func (n Macro) String() string { return orgWriter.WriteNodesAsString(n) }
func (n Timestamp) String() string { return orgWriter.WriteNodesAsString(n) }