forked from mikaelbr/marked-terminal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
668 lines (573 loc) · 16.8 KB
/
index.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
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
'use strict';
import chalk from 'chalk';
import Table from 'cli-table3';
import { highlight as highlightCli } from 'cli-highlight';
import * as emoji from 'node-emoji';
import ansiEscapes from 'ansi-escapes';
import supportsHyperlinks from 'supports-hyperlinks';
var TABLE_CELL_SPLIT = '^*||*^';
var TABLE_ROW_WRAP = '*|*|*|*';
var TABLE_ROW_WRAP_REGEXP = new RegExp(escapeRegExp(TABLE_ROW_WRAP), 'g');
var COLON_REPLACER = '*#COLON|*';
var COLON_REPLACER_REGEXP = new RegExp(escapeRegExp(COLON_REPLACER), 'g');
var TAB_ALLOWED_CHARACTERS = ['\t'];
// HARD_RETURN holds a character sequence used to indicate text has a
// hard (no-reflowing) line break. Previously \r and \r\n were turned
// into \n in marked's lexer- preprocessing step. So \r is safe to use
// to indicate a hard (non-reflowed) return.
var HARD_RETURN = '\r',
HARD_RETURN_RE = new RegExp(HARD_RETURN),
HARD_RETURN_GFM_RE = new RegExp(HARD_RETURN + '|<br />');
var defaultOptions = {
code: chalk.yellow,
blockquote: chalk.gray.italic,
html: chalk.gray,
heading: chalk.green.bold,
firstHeading: chalk.magenta.underline.bold,
hr: chalk.reset,
listitem: chalk.reset,
list: list,
table: chalk.reset,
paragraph: chalk.reset,
strong: chalk.bold,
em: chalk.italic,
codespan: chalk.yellow,
del: chalk.dim.gray.strikethrough,
link: chalk.blue,
href: chalk.blue.underline,
text: identity,
unescape: true,
emoji: true,
width: 80,
showSectionPrefix: true,
reflowText: false,
tab: 4,
tableOptions: {}
};
function Renderer(options, highlightOptions) {
this.o = Object.assign({}, defaultOptions, options);
this.tab = sanitizeTab(this.o.tab, defaultOptions.tab);
this.tableSettings = this.o.tableOptions;
this.emoji = this.o.emoji ? insertEmojis : identity;
this.unescape = this.o.unescape ? unescapeEntities : identity;
this.highlightOptions = highlightOptions || {};
this.transform = compose(undoColon, this.unescape, this.emoji);
}
// Compute length of str not including ANSI escape codes.
// See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
function textLength(str) {
return str.replace(/\u001b\[(?:\d{1,3})(?:;\d{1,3})*m/g, '').length;
}
Renderer.prototype.textLength = textLength;
function fixHardReturn(text, reflow) {
return reflow ? text.replace(HARD_RETURN, /\n/g) : text;
}
Renderer.prototype.space = function () {
return '';
};
Renderer.prototype.text = function (text) {
if (typeof text === 'object') {
text = text.text;
}
return this.o.text(text);
};
Renderer.prototype.code = function (code, lang, escaped) {
if (typeof code === 'object') {
lang = code.lang;
escaped = !!code.escaped;
code = code.text;
}
return section(
indentify(this.tab, highlight(code, lang, this.o, this.highlightOptions))
);
};
Renderer.prototype.blockquote = function (quote) {
if (typeof quote === 'object') {
quote = this.parser.parse(quote.tokens);
}
return section(this.o.blockquote(indentify(this.tab, quote.trim())));
};
Renderer.prototype.html = function (html) {
if (typeof html === 'object') {
html = html.text;
}
return this.o.html(html);
};
Renderer.prototype.heading = function (text, level) {
if (typeof text === 'object') {
level = text.depth;
text = this.parser.parseInline(text.tokens);
}
text = this.transform(text);
var prefix = this.o.showSectionPrefix
? new Array(level + 1).join('#') + ' '
: '';
text = prefix + text;
if (this.o.reflowText) {
text = reflowText(text, this.o.width, this.options.gfm);
}
return section(
level === 1 ? this.o.firstHeading(text) : this.o.heading(text)
);
};
Renderer.prototype.hr = function () {
return section(this.o.hr(hr('-', this.o.reflowText && this.o.width)));
};
Renderer.prototype.list = function (body, ordered) {
if (typeof body === 'object') {
const listToken = body;
const start = listToken.start;
const loose = listToken.loose;
ordered = listToken.ordered;
body = '';
for (let j = 0; j < listToken.items.length; j++) {
body += this.listitem(listToken.items[j]);
}
}
body = this.o.list(body, ordered, this.tab);
return section(fixNestedLists(indentLines(this.tab, body), this.tab));
};
Renderer.prototype.listitem = function (text) {
if (typeof text === 'object') {
const item = text;
text = '';
if (item.task) {
const checkbox = this.checkbox({ checked: !!item.checked });
if (item.loose) {
if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
}
} else {
item.tokens.unshift({
type: 'text',
raw: checkbox + ' ',
text: checkbox + ' '
});
}
} else {
text += checkbox + ' ';
}
}
text += this.parser.parse(item.tokens, !!item.loose);
}
var transform = compose(this.o.listitem, this.transform);
var isNested = text.indexOf('\n') !== -1;
if (isNested) text = text.trim();
// Use BULLET_POINT as a marker for ordered or unordered list item
return '\n' + BULLET_POINT + transform(text);
};
Renderer.prototype.checkbox = function (checked) {
if (typeof checked === 'object') {
checked = checked.checked;
}
return '[' + (checked ? 'X' : ' ') + '] ';
};
Renderer.prototype.paragraph = function (text) {
if (typeof text === 'object') {
text = this.parser.parseInline(text.tokens);
}
var transform = compose(this.o.paragraph, this.transform);
text = transform(text);
if (this.o.reflowText) {
text = reflowText(text, this.o.width, this.options.gfm);
}
return section(text);
};
Renderer.prototype.table = function (header, body) {
if (typeof header === 'object') {
const token = header;
header = '';
// header
let cell = '';
for (let j = 0; j < token.header.length; j++) {
cell += this.tablecell(token.header[j]);
}
header += this.tablerow({ text: cell });
body = '';
for (let j = 0; j < token.rows.length; j++) {
const row = token.rows[j];
cell = '';
for (let k = 0; k < row.length; k++) {
cell += this.tablecell(row[k]);
}
body += this.tablerow({ text: cell });
}
if (body) body = `<tbody>${body}</tbody>`;
}
var table = new Table(
Object.assign(
{},
{
head: generateTableRow(header)[0]
},
this.tableSettings
)
);
generateTableRow(body, this.transform).forEach(function (row) {
table.push(row);
});
return section(this.o.table(table.toString()));
};
Renderer.prototype.tablerow = function (content) {
if (typeof content === 'object') {
content = content.text;
}
return TABLE_ROW_WRAP + content + TABLE_ROW_WRAP + '\n';
};
Renderer.prototype.tablecell = function (content) {
if (typeof content === 'object') {
content = this.parser.parseInline(content.tokens);
}
return content + TABLE_CELL_SPLIT;
};
// span level renderer
Renderer.prototype.strong = function (text) {
if (typeof text === 'object') {
text = this.parser.parseInline(text.tokens);
}
return this.o.strong(text);
};
Renderer.prototype.em = function (text) {
if (typeof text === 'object') {
text = this.parser.parseInline(text.tokens);
}
text = fixHardReturn(text, this.o.reflowText);
return this.o.em(text);
};
Renderer.prototype.codespan = function (text) {
if (typeof text === 'object') {
text = text.text;
}
text = fixHardReturn(text, this.o.reflowText);
return this.o.codespan(text.replace(/:/g, COLON_REPLACER));
};
Renderer.prototype.br = function () {
return this.o.reflowText ? HARD_RETURN : '\n';
};
Renderer.prototype.del = function (text) {
if (typeof text === 'object') {
text = this.parser.parseInline(text.tokens);
}
return this.o.del(text);
};
Renderer.prototype.link = function (href, title, text) {
if (typeof href === 'object') {
title = href.title;
text = this.parser.parseInline(href.tokens);
href = href.href;
}
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.indexOf('javascript:') === 0) {
return '';
}
}
var hasText = text && text !== href;
var out = '';
if (supportsHyperlinks.stdout) {
let link = '';
if (text) {
link = this.o.href(this.emoji(text));
} else {
link = this.o.href(href);
}
out = ansiEscapes.link(link, href);
} else {
if (hasText) out += this.emoji(text) + ' (';
out += this.o.href(href);
if (hasText) out += ')';
}
return this.o.link(out);
};
Renderer.prototype.image = function (href, title, text) {
if (typeof href === 'object') {
title = href.title;
text = href.text;
href = href.href;
}
if (typeof this.o.image === 'function') {
return this.o.image(href, title, text);
}
var out = '![' + text;
if (title) out += ' – ' + title;
return out + '](' + href + ')\n';
};
export default Renderer;
export function markedTerminal(options, highlightOptions) {
const r = new Renderer(options, highlightOptions);
const funcs = [
'text',
'code',
'blockquote',
'html',
'heading',
'hr',
'list',
'listitem',
'checkbox',
'paragraph',
'table',
'tablerow',
'tablecell',
'strong',
'em',
'codespan',
'br',
'del',
'link',
'image'
];
return funcs.reduce(
(extension, func) => {
extension.renderer[func] = function (...args) {
r.options = this.options;
r.parser = this.parser;
return r[func](...args);
};
return extension;
},
{ renderer: {}, useNewRenderer: true }
);
}
// Munge \n's and spaces in "text" so that the number of
// characters between \n's is less than or equal to "width".
function reflowText(text, width, gfm) {
// Hard break was inserted by Renderer.prototype.br or is
// <br /> when gfm is true
var splitRe = gfm ? HARD_RETURN_GFM_RE : HARD_RETURN_RE,
sections = text.split(splitRe),
reflowed = [];
sections.forEach(function (section) {
// Split the section by escape codes so that we can
// deal with them separately.
var fragments = section.split(/(\u001b\[(?:\d{1,3})(?:;\d{1,3})*m)/g);
var column = 0;
var currentLine = '';
var lastWasEscapeChar = false;
while (fragments.length) {
var fragment = fragments[0];
if (fragment === '') {
fragments.splice(0, 1);
lastWasEscapeChar = false;
continue;
}
// This is an escape code - leave it whole and
// move to the next fragment.
if (!textLength(fragment)) {
currentLine += fragment;
fragments.splice(0, 1);
lastWasEscapeChar = true;
continue;
}
var words = fragment.split(/[ \t\n]+/);
for (var i = 0; i < words.length; i++) {
var word = words[i];
var addSpace = column != 0;
if (lastWasEscapeChar) addSpace = false;
// If adding the new word overflows the required width
if (column + word.length + addSpace > width) {
if (word.length <= width) {
// If the new word is smaller than the required width
// just add it at the beginning of a new line
reflowed.push(currentLine);
currentLine = word;
column = word.length;
} else {
// If the new word is longer than the required width
// split this word into smaller parts.
var w = word.substr(0, width - column - addSpace);
if (addSpace) currentLine += ' ';
currentLine += w;
reflowed.push(currentLine);
currentLine = '';
column = 0;
word = word.substr(w.length);
while (word.length) {
var w = word.substr(0, width);
if (!w.length) break;
if (w.length < width) {
currentLine = w;
column = w.length;
break;
} else {
reflowed.push(w);
word = word.substr(width);
}
}
}
} else {
if (addSpace) {
currentLine += ' ';
column++;
}
currentLine += word;
column += word.length;
}
lastWasEscapeChar = false;
}
fragments.splice(0, 1);
}
if (textLength(currentLine)) reflowed.push(currentLine);
});
return reflowed.join('\n');
}
function indentLines(indent, text) {
return text.replace(/(^|\n)(.+)/g, '$1' + indent + '$2');
}
function indentify(indent, text) {
if (!text) return text;
return indent + text.split('\n').join('\n' + indent);
}
var BULLET_POINT_REGEX = '\\*';
var NUMBERED_POINT_REGEX = '\\d+\\.';
var POINT_REGEX =
'(?:' + [BULLET_POINT_REGEX, NUMBERED_POINT_REGEX].join('|') + ')';
// Prevents nested lists from joining their parent list's last line
function fixNestedLists(body, indent) {
var regex = new RegExp(
'' +
'(\\S(?: | )?)' + // Last char of current point, plus one or two spaces
// to allow trailing spaces
'((?:' +
indent +
')+)' + // Indentation of sub point
'(' +
POINT_REGEX +
'(?:.*)+)$',
'gm'
); // Body of subpoint
return body.replace(regex, '$1\n' + indent + '$2$3');
}
var isPointedLine = function (line, indent) {
return line.match('^(?:' + indent + ')*' + POINT_REGEX);
};
function toSpaces(str) {
return ' '.repeat(str.length);
}
var BULLET_POINT = '* ';
function bulletPointLine(indent, line) {
return isPointedLine(line, indent) ? line : toSpaces(BULLET_POINT) + line;
}
function bulletPointLines(lines, indent) {
var transform = bulletPointLine.bind(null, indent);
return lines.split('\n').filter(identity).map(transform).join('\n');
}
var numberedPoint = function (n) {
return n + '. ';
};
function numberedLine(indent, line, num) {
return isPointedLine(line, indent)
? {
num: num + 1,
line: line.replace(BULLET_POINT, numberedPoint(num + 1))
}
: {
num: num,
line: toSpaces(numberedPoint(num)) + line
};
}
function numberedLines(lines, indent) {
var transform = numberedLine.bind(null, indent);
let num = 0;
return lines
.split('\n')
.filter(identity)
.map((line) => {
const numbered = transform(line, num);
num = numbered.num;
return numbered.line;
})
.join('\n');
}
function list(body, ordered, indent) {
body = body.trim();
body = ordered ? numberedLines(body, indent) : bulletPointLines(body, indent);
return body;
}
function section(text) {
return text + '\n\n';
}
function highlight(code, language, opts, hightlightOpts) {
if (chalk.level === 0) return code;
var style = opts.code;
code = fixHardReturn(code, opts.reflowText);
try {
return highlightCli(code, Object.assign({}, { language }, hightlightOpts));
} catch (e) {
return style(code);
}
}
function insertEmojis(text) {
return text.replace(/:([A-Za-z0-9_\-\+]+?):/g, function (emojiString) {
var emojiSign = emoji.get(emojiString);
if (!emojiSign) return emojiString;
return emojiSign + ' ';
});
}
function hr(inputHrStr, length) {
length = length || process.stdout.columns;
return new Array(length).join(inputHrStr);
}
function undoColon(str) {
return str.replace(COLON_REPLACER_REGEXP, ':');
}
function generateTableRow(text, escape) {
if (!text) return [];
escape = escape || identity;
var lines = escape(text).split('\n');
var data = [];
lines.forEach(function (line) {
if (!line) return;
var parsed = line
.replace(TABLE_ROW_WRAP_REGEXP, '')
.split(TABLE_CELL_SPLIT);
data.push(parsed.splice(0, parsed.length - 1));
});
return data;
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
function unescapeEntities(html) {
return html
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
function identity(str) {
return str;
}
function compose() {
var funcs = arguments;
return function () {
var args = arguments;
for (var i = funcs.length; i-- > 0; ) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
}
function isAllowedTabString(string) {
return TAB_ALLOWED_CHARACTERS.some(function (char) {
return string.match('^(' + char + ')+$');
});
}
function sanitizeTab(tab, fallbackTab) {
if (typeof tab === 'number') {
return new Array(tab + 1).join(' ');
} else if (typeof tab === 'string' && isAllowedTabString(tab)) {
return tab;
} else {
return new Array(fallbackTab + 1).join(' ');
}
}