-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmrk.js
348 lines (283 loc) · 10 KB
/
mrk.js
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
(function() {
'use strict'
function factory({ patterns, extendPatterns, pairs, extendPairs, htmlify, extendHtmlify } = {}) {
function mrk(input) {
function tokenize(input) {
const tokens = []
// Match patterns
for (let index = 0; index < input.length; index++) {
const indexBefore = index
let match = null, metadata = undefined
for (const [ matchName, fn ] of Object.entries(mrk.patterns)) {
metadata = undefined
const isMatch = fn({
read(n = 1) {
// Read `n` characters
const chars = input.substr(index, n)
index += n
return chars
},
readUntil(c, orEnd = false) {
// Read until we encounter the character `c`
let buf = ''
for (let i = index; i < input.length; i++) {
if(c.constructor === String) {
if (input[i] === c) {
index += buf.length
return buf
}
} else if (c.constructor === Array) {
if (c.includes(input[i])) {
index += buf.length
return buf
}
} else if (c.constructor === RegExp) {
if (c.test(input[i])) {
index += buf.length
return buf
}
} else {
throw "Firt argument to readUntil must be of type String, Array, or RegExp"
}
buf += input[i]
}
if (orEnd) {
index += buf.length
return buf
} else {
return null // We did not encounter `c`
}
},
look(n = 1) {
// Read `n` characters ahead - don't change `index`
return input.substr(index, n)
},
rewind(n = 1) {
// Go back `n` characters
index -= n
},
has(token, beforeToken) {
// Search for `token` before the first `beforeToken`, backwards
for (let i = tokens.length - 1; i >= 0; i--) {
const { name } = tokens[i]
if (name === beforeToken) return false
if (name === token) return true
}
return false
},
}, obj => {
// Set metadata
metadata = obj
})
if (isMatch) {
// Match!
match = matchName
break
} else {
// No match, so let's try the next pattern
index = indexBefore // Rewind
}
}
if (match) {
// We matched with something! Let's add it to the token list
tokens.push({
name: match,
text: input.substr(indexBefore, index - indexBefore),
indexStart: indexBefore,
indexEnd: --index, // The loop will do index++, so we need to go back a character
metadata,
})
} else {
// No match -- it must be text
const lastToken = tokens[tokens.length - 1]
const char = input[index]
if (lastToken && lastToken.name === 'text') {
// Extend the last text token with this char
lastToken.text += char
lastToken.indexEnd += char.length
} else {
// New text token
tokens.push({
name: 'text',
text: char,
indexStart: indexBefore,
indexEnd: indexBefore + char.length,
metadata: { lonePair: false },
})
}
}
}
// Make sure pairs are actually in pairs
for (let t = 0; t < tokens.length; t++) {
const token = tokens[t]
let endingName, hasPair = false
if (endingName = mrk.pairs[token.name]) {
// Search for `endingName` before the next token of the same name
for (let j = t + 1; j < tokens.length; j++) {
const jtoken = tokens[j]
if (jtoken.name === token.name) {
// Nope. We've reached the next token of the same name, so
// this token does NOT have a pair token :(
break
} else if (jtoken.name === endingName) {
// We found a pair token!!
hasPair = true
break
}
}
if (!hasPair) {
// Revert `token` to a text token, as it does not have a pair
token.name = 'text'
token.metadata = { lonePair: true }
}
}
}
return tokens
}
const tokens = tokenize(input)
return {
tokens,
html() {
let html = ''
const htmlify = mrk.htmlify
for (const token of tokens) {
html += mrk.htmlify[token.name](token)
}
return html
}
}
}
// Escapes special chars in text for rendering to HTML
mrk.escapeHTML = text => {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
// Force a URL to be safe from schemas which can evaluate scripts
mrk.sanitizeURL = url => {
url = url.trim()
switch (url.toLowerCase().split(/(:|\/\/)/)[0]) {
case "http":
case "https":
case "":
return url
default:
return "http://" + url
}
}
// Extend mrk by adding functions to the pattern obj, or removing
// them, or whatever.
mrk.patterns = patterns || Object.assign({
// \n
newline({ read }) {
return read() === '\n'
},
// *italic...
italicStart({ read, look, has }) {
return read() === '*' // Must be single asterisk
&& look() !== '*' // Not bold (double asterisk)
&& !has('italicStart', 'italicEnd') // Not already italics
},
// ...italic*
italicEnd({ read, look, has }) {
return read() === '*' // Single asterisk
&& look() !== '*' // Not bold (double asterisk)
&& has('italicStart', 'italicEnd') // Currently italics
},
// _italic...
italicUnderscoredStart({ read, look, has }) {
return read() === '_' // Must be single underscore
&& !has('italicUnderscoredStart', 'italicUnderscoredEnd') // Not already _italics_
},
// ...italic_
italicUnderscoredEnd({ read, look, has }) {
return read() === '_' // Must be single underscore
&& has('italicUnderscoredStart', 'italicUnderscoredEnd') // Currently _italics_
},
// **bold...
boldStart({ read, look, has }) {
return read(2) === '**' // 2 asterisks
&& !has('boldStart', 'boldEnd') // Not already bold
},
// ...bold**
boldEnd({ read, look, has }) {
return read(2) === '**' // 2 asterisks
&& has('boldStart', 'boldEnd') // Currently bold
},
// `code`
code({ read, has }) {
if(read() === '`') {
// Eat up every character until another backtick
let escaped = false, char
while (char = read()) {
if (char === '\\' && !escaped) escaped = true
else if (char === '`' && !escaped) return true
else escaped = false
}
}
},
// [name](href)
link({ read, readUntil }, meta) {
if (read() !== '[') return
// All characters up to `]` are the link name
const name = readUntil(']')
if (read(2) !== '](') return
// All characters up to `)` are the link href
const href = readUntil(')')
// Set metadata
meta({ name, href })
return read() === ')'
},
// http[s]://url
autolink({ read, readUntil, rewind }) {
// Should start with http:// or https://
if (read(4) !== 'http') return
if (read(1) !== 's') rewind(1)
if (read(3) !== '://') return
// Eat everything until a whitespace; we can assume that this is a valid URL
readUntil(/\s/, true)
return true
},
}, extendPatterns || {})
// Tokens that will be reverted to text if they do not see their paired ending token
// e.g. italicStart without an italicEnd will become text (with metadata.lonePair = true)
mrk.pairs = pairs || Object.assign({
italicStart: 'italicEnd',
italicUnderscoredStart: 'italicUnderscoredEnd',
boldStart: 'boldEnd',
}, extendPairs || {})
// Declares how to HTML-ify tokens.
mrk.htmlify = htmlify || Object.assign({
// text
text: ({ text }) => mrk.escapeHTML(text),
// newline
newline: () => '<br/>',
// *italic* -> <i>
italicStart: () => '<i>',
italicEnd: () => '</i>',
// _italic_ -> <em>
italicUnderscoredStart: () => '<em>',
italicUnderscoredEnd: () => '</em>',
// **bold** -> <b>
boldStart: () => '<b>',
boldEnd: () => '</b>',
// `code` -> <code>
code: ({ text }) => '<code>' + mrk.escapeHTML(text.substr(1, text.length - 2)) + '</code>',
// [name](href) -> <a>
link: ({ metadata }) => `<a href='${mrk.sanitizeURL(mrk.escapeHTML(metadata.href))}'>${mrk.escapeHTML(metadata.name)}</a>`,
// autolinked -> <a>
autolink: ({ text }) => `<a href='${mrk.escapeHTML(text)}'>${mrk.escapeHTML(text)}</a>`,
}, extendHtmlify || {})
return mrk
}
if (typeof module === 'object' && module.exports) {
module.exports = factory
} else if (typeof global === 'object') {
global.mrk = factory
} else if (window) {
window.mrk = factory
}
})()