forked from segmentfault/HyperDown.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhyperdown.js
More file actions
6596 lines (5728 loc) · 201 KB
/
Copy pathhyperdown.js
File metadata and controls
6596 lines (5728 loc) · 201 KB
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/**
* Parser in ECMAScript 6
*
* @copyright Copyright (c) 2012 SegmentFault Team. (http://segmentfault.com)
* @author Integ <integ@segmentfault.com>
* @license BSD License
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
__webpack_require__(1);
var _md5 = __webpack_require__(185);
var _md52 = _interopRequireDefault(_md5);
var Parser = (function () {
function Parser() {
_classCallCheck(this, Parser);
this.commonWhiteList = 'kbd|b|i|strong|em|sup|sub|br|code|del|a|hr|small';
this.specialWhiteList = {
table: 'table|tbody|thead|tfoot|tr|td|th'
};
this.footnotes = [];
this.blocks = [];
this.current = 'normal';
this.pos = -1;
this.definitions = [];
this.hooks = {};
this.holders = new Map();
this.uniqid = (0, _md52['default'])(new Date().getTime());
this.id = 0;
}
/**
* makeHtml
*
* @param mixed text
* @return string
*/
_createClass(Parser, [{
key: 'makeHtml',
value: function makeHtml(text) {
text = this.initText(text);
var html = this.parse(text);
html = this.makeFootnotes(html);
if (this.hooks.afterParse) {
html = this.call('afterParse', html);
}
return html;
}
/**
* @param type
* @param callback
*/
}, {
key: 'hook',
value: function hook(type, callback) {
if (this.hooks[type]) {
this.hooks[type].push(callback);
} else {
this.hooks[type] = [callback];
}
}
/**
* @param str
* @return string
*/
}, {
key: 'makeHolder',
value: function makeHolder(str) {
var key = '|\r' + this.uniqid + this.id + '\r|';
this.id++;
this.holders[key] = str;
return key;
}
/**
* @param text
* @return mixed
*/
}, {
key: 'initText',
value: function initText(text) {
if (text) {
text = text.replace(/\t/g, ' ');
text = text.replace(/\r/g, '');
} else {
text = '';
}
return text;
}
/**
* @param html
* @return string
*/
}, {
key: 'makeFootnotes',
value: function makeFootnotes(html) {
if (this.footnotes.length > 0) {
html += '<div class="footnotes"><hr><ol>';
var index = 1;
var val = this.footnotes.shift();
while (val) {
if (typeof val === 'string') {
val += ' <a href="#fnref-' + index + '" class="footnote-backref">↩</a>';
} else {
val[val.length - 1] += ' <a href="#fnref-' + index + '" class="footnote-backref">↩</a>';
val = val.length > 1 ? this.parse(val.join("\n")) : this.parseInline(val[0]);
}
html += '<li id="fn-' + index + '">' + val + '</li>';
index++;
val = this.footnotes.shift();
}
html += '</ol></div>';
}
return html;
}
/**
* parse
*
* @param string text
* @return string
*/
}, {
key: 'parse',
value: function parse(text) {
var _this2 = this;
var lines = text.split("\n");
var blocks = this.parseBlock(text, lines);
var html = '';
blocks.forEach(function (block) {
var _block = _slicedToArray(block, 4);
var type = _block[0];
var start = _block[1];
var end = _block[2];
var value = _block[3];
var extract = lines.slice(start, end + 1);
var method = 'parse' + type.slice(0, 1).toUpperCase() + type.slice(1);
var beforeMethod = 'beforeParse' + type.slice(0, 1).toUpperCase() + type.slice(1);
extract = _this2.call(beforeMethod, extract, value);
var result = _this2[method](extract, value);
result = _this2.call('after' + method.slice(0, 1).toUpperCase() + method.slice(1), result, value);
html += result;
});
return html;
}
/**
* @param type
* @param value
* @return mixed
*/
}, {
key: 'call',
value: function call(type, value) {
if (!this.hooks[type]) {
return value;
}
var args = [].slice.call(arguments);
args = args.slice(1);
this.hooks[type].forEach(function (callback) {
value = callback.apply(null, args);
args[0] = value;
});
return value;
}
/**
* @param text
* @param clearHolders
* @return string
*/
}, {
key: 'releaseHolder',
value: function releaseHolder(text) {
var clearHolders = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
var deep = 0;
while (text.indexOf("|\r") !== -1 && deep < 10) {
for (var key in this.holders) {
var value = this.holders[key];
text = text.replace(key, value);
}
deep++;
}
if (clearHolders) {
this.holders.clear();
}
return text;
}
/**
* parseInline
*
* @param string text
* @param string whiteList
* @param bool clearHolders
* @return string
*/
}, {
key: 'parseInline',
value: function parseInline(text) {
var _this3 = this;
var whiteList = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
var clearHolders = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
text = this.call('beforeParseInline', text);
var _this = this;
// code
text = text.replace(/(^|[^\\])(`+)(.+?)\2/g, function (match, p1, p2, p3) {
return p1 + _this.makeHolder('<code>' + _this.htmlspecialchars(p3) + '</code>');
});
// link
text = text.replace(/<(https?:\/\/.+)>/ig, function (match, p1) {
return _this3.makeHolder('<a href="' + p1 + '">' + p1 + '</a>');
});
text = text.replace(/<(\/?)([a-z0-9-]+)(\s+[^>]*)?>/ig, function (match, p1, p2, p3) {
var whiteLists = _this3.commonWhiteList + '|' + whiteList;
if (whiteLists.toLowerCase().indexOf(p2.toLowerCase()) !== -1) {
return _this3.makeHolder(match);
} else {
return _this3.htmlspecialchars(match);
}
});
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
// footnote
var footnotePattern = /\[\^((?:[^\]]|\]|\[)+?)\]/g;
text = text.replace(footnotePattern, function (match, p1, p2) {
var id = _this.footnotes.indexOf(p1);
if (id === -1) {
id = _this.footnotes.length;
_this.footnotes.push(_this3.parseInline(p1, '', false));
}
return _this.makeHolder('<sup id="fnref-' + (id + 1) + '"><a href="#fn-' + (id + 1) + '" class="footnote-ref">' + (id + 1) + '</a></sup>');
});
// image
var imagePattern1 = /!\[((?:[^\]]|\]|\[)*?)\]\(((?:[^\)]|\)|\()+?)\)/g;
text = text.replace(imagePattern1, function (match, p1, p2) {
var escaped = _this.escapeBracket(p1);
var url = _this.escapeBracket(p2);
return _this.makeHolder('<img src="' + url + '" alt="' + escaped + '" title="' + escaped + '">');
});
var imagePattern2 = /!\[((?:[^\]]|\]|\[)*?)\]\[((?:[^\]]|\]|\[)+?)\]/g;
text = text.replace(imagePattern2, function (match, p1, p2) {
var escaped = _this.escapeBracket(p1);
var result = '';
if (_this.definitions[p2]) {
result = '<img src="' + _this.definitions[p2] + '" alt="' + escaped + '" title="' + escaped + '">';
} else {
result = escaped;
}
return _this.makeHolder(result);
});
// link
var linkPattern1 = /\[((?:[^\]]|\]|\[)+?)\]\(((?:[^\)]|\)|\()+?)\)/g;
text = text.replace(linkPattern1, function (match, p1, p2) {
var escaped = _this.parseInline(_this.escapeBracket(p1), '', false);
var url = _this.escapeBracket(p2);
return _this.makeHolder('<a href="' + url + '">' + escaped + '</a>');
});
var linkPattern2 = /\[((?:[^\]]|\]|\[)+?)\]\[((?:[^\]]|\]|\[)+?)\]/g;
text = text.replace(linkPattern2, function (match, p1, p2) {
var escaped = _this.parseInline(_this.escapeBracket(p1), '', false);
var result = _this.definitions[p2] ? '<a href="' + _this.definitions[p2] + '">' + escaped + '</a>' : escaped;
return _this.makeHolder(result);
});
// escape
text = text.replace(/\\(`|\*|_|~)/g, function (match, p1) {
return _this.makeHolder(_this.htmlspecialchars(p1));
});
// strong and em and some fuck
text = this.parseInlineCallback(text);
text = text.replace(/<([_a-z0-9-\.\+]+@[^@]+\.[a-z]{2,})>/ig, "<a href=\"mailto:$1\">$1</a>");
// autolink url
text = text.replace(/(^|[^"])((http|https|ftp|mailto):[_a-z0-9-\.\/%#@\?\+=~\|\,&\(\)]+)($|[^"])/ig, "$1<a href=\"$2\">$2</a>$4");
text = this.call('afterParseInlineBeforeRelease', text);
// release
text = this.releaseHolder(text, clearHolders);
text = this.call('afterParseInline', text);
return text;
}
/**
* @param text
* @return mixed
*/
}, {
key: 'parseInlineCallback',
value: function parseInlineCallback(text) {
var _this4 = this;
text = text.replace(/(\*{3})(.+?)\1/g, function (match, p1, p2) {
return '<strong><em>' + _this4.parseInlineCallback(p2) + '</em></strong>';
});
text = text.replace(/(\*{2})(.+?)\1/g, function (match, p1, p2) {
return '<strong>' + _this4.parseInlineCallback(p2) + '</strong>';
});
text = text.replace(/(\*)(.+?)\1/g, function (match, p1, p2) {
return '<em>' + _this4.parseInlineCallback(p2) + '</em>';
});
text = text.replace(/(\s+|^)(_{3})(.+?)\2(\s+|$)/g, function (match, p1, p2, p3, p4) {
return p1 + '<strong><em>' + _this4.parseInlineCallback(p3) + '</em></strong>' + p4;
});
text = text.replace(/(\s+|^)(_{2})(.+?)\2(\s+|$)/g, function (match, p1, p2, p3, p4) {
return p1 + '<strong>' + _this4.parseInlineCallback(p3) + '</strong>' + p4;
});
text = text.replace(/(\s+|^)(_)(.+?)\2(\s+|$)/g, function (match, p1, p2, p3, p4) {
return p1 + '<em>' + _this4.parseInlineCallback(p3) + '</em>' + p4;
});
text = text.replace(/(~{2})(.+?)\1/g, function (match, p1, p2) {
return '<del>' + _this4.parseInlineCallback(p2) + '</del>';
});
return text;
}
/**
* parseBlock
*
* @param string text
* @param array lines
* @return array
*/
}, {
key: 'parseBlock',
value: function parseBlock(text, lines) {
var _this5 = this;
this.blocks = [];
this.current = 'normal';
this.pos = -1;
var special = Object.keys(this.specialWhiteList).join("|");
var emptyCount = 0;
// analyze by line
for (var key in lines) {
key = parseInt(key); // ES6 的 for key in Array 循环时返回的 key 是字符串,不是 int
var line = lines[key];
// code block is special
var codeMatches = line.match(/^(\s*)(~|`){3,}([^`~]*)$/i);
if (codeMatches) {
if (this.isBlock('code')) {
var block = this.getBlock();
var isAfterList = block[3][2];
if (isAfterList) {
this.combineBlock().setBlock(key);
} else {
this.setBlock(key).endBlock();
}
} else {
var isAfterList = false;
if (this.isBlock('list')) {
var block = this.getBlock();
var space = block[3];
isAfterList = space > 0 && codeMatches[1].length >= space || codeMatches[1].length > space;
}
this.startBlock('code', key, [codeMatches[1], codeMatches[3], isAfterList]);
}
continue;
} else if (this.isBlock('code')) {
this.setBlock(key);
continue;
}
// html block is special too
var htmlPattern1 = new RegExp('^\s*<(' + special + ')(\s+[^>]*)?>', 'i');
var htmlPattern2 = new RegExp('<\/(' + special + ')>\s*$', 'i');
var htmlMatches1 = line.match(htmlPattern1);
var htmlMatches2 = line.match(htmlPattern2);
if (htmlMatches1) {
var tag = htmlMatches1[1].toLowerCase();
if (!this.isBlock('html', tag) && !this.isBlock('pre')) {
this.startBlock('html', key, tag);
}
continue;
} else if (htmlMatches2) {
var tag = htmlMatches2[1].toLowerCase();
if (this.isBlock('html', tag)) {
this.setBlock(key).endBlock();
}
continue;
} else if (this.isBlock('html')) {
this.setBlock(key);
continue;
}
switch (true) {
// list
case /^(\s*)((?:[0-9a-z]\.)|\-|\+|\*)\s+/.test(line):
var matches = line.match(/^(\s*)((?:[0-9a-z]\.)|\-|\+|\*)\s+/);
var listSpace = matches[1].length;
emptyCount = 0;
// opened
if (this.isBlock('list')) {
this.setBlock(key, listSpace);
} else {
this.startBlock('list', key, listSpace);
}
break;
// footnote
case /^\[\^((?:[^\]]|\]|\[)+?)\]:/.test(line):
var footnoteMatches = /^\[\^((?:[^\]]|\]|\[)+?)\]:/.exec(line);
var footnoteSpace = footnoteMatches[0].length - 1;
this.startBlock('footnote', key, [footnoteSpace, footnoteMatches[1]]);
break;
// definition
case /^\s*\[((?:[^\]]|\]|\[)+?)\]:\s*(.+)$/.test(line):
var definitionMatches = line.match(/^\s*\[((?:[^\]]|\]|\[)+?)\]:\s*(.+)$/);
this.definitions[definitionMatches[1]] = definitionMatches[2];
this.startBlock('definition', key).endBlock();
break;
// block quote
case /^\s*>/.test(line):
if (this.isBlock('quote')) {
this.setBlock(key);
} else {
this.startBlock('quote', key);
}
break;
// pre
case /^ {4}/.test(line):
emptyCount = 0;
if (this.isBlock('pre') || this.isBlock('list')) {
this.setBlock(key);
} else if (this.isBlock('normal')) {
this.startBlock('pre', key);
}
break;
// table
case /^((?:(?:(?:[ :]*\-[ :]*)+(?:\||\+))|(?:(?:\||\+)(?:[ :]*\-[ :]*)+)|(?:(?:[ :]*\-[ :]*)+(?:\||\+)(?:[ :]*\-[ :]*)+))+)$/g.test(line):
var tableMatches = /^((?:(?:(?:[ :]*\-[ :]*)+(?:\||\+))|(?:(?:\||\+)(?:[ :]*\-[ :]*)+)|(?:(?:[ :]*\-[ :]*)+(?:\||\+)(?:[ :]*\-[ :]*)+))+)$/g.exec(line);
if (this.isBlock('normal')) {
(function () {
var block = _this5.getBlock();
var head = false;
if (block.length === 0 || block[0] !== 'normal' || /^\s*$/.test(lines[block[2]])) {
_this5.startBlock('table', key);
} else {
head = true;
_this5.backBlock(1, 'table');
}
if (tableMatches[1][0] == '|') {
tableMatches[1] = tableMatches[1].substr(1);
if (tableMatches[1][tableMatches[1].length - 1] == '|') {
tableMatches[1] = tableMatches[1].slice(0, -1);
}
}
var rows = tableMatches[1].split(/[\+|\|]/);
var aligns = [];
rows.forEach(function (row) {
var align = 'none';
var tableMatches = row.match(/^\s*(:?)\-+(:?)\s*$/);
if (tableMatches) {
if (tableMatches[1] == tableMatches[2]) {
align = 'center';
} else if (tableMatches[1]) {
align = 'left';
} else if (tableMatches[2]) {
align = 'right';
}
}
aligns.push(align);
});
_this5.setBlock(key, [head, aligns]);
})();
}
break;
// single heading
case /^(#+)(.*)$/.test(line):
var singleHeadingMatches = line.match(/^(#+)(.*)$/);
var num = Math.min(singleHeadingMatches[1].length, 6);
this.startBlock('sh', key, num).endBlock();
break;
// multi heading
case /^\s*((=|-){2,})\s*$/.test(line) && (this.getBlock() && this.getBlock()[0] === 'normal' && !/^\s*$/.test(lines[this.getBlock()[2]])):
// check if last line isn't empty
var multiHeadingMatches = line.match(/^\s*((=|-){2,})\s*$/);
if (this.isBlock('normal')) {
this.backBlock(1, 'mh', multiHeadingMatches[1][0] == '=' ? 1 : 2).setBlock(key).endBlock();
} else {
this.startBlock('normal', key);
}
break;
// hr
case /^[-\*]{3,}\s*$/.test(line):
this.startBlock('hr', key).endBlock();
break;
// normal
default:
if (this.isBlock('list')) {
// let matches = line.match(/^(\s*)/)
//
// if (line.length == matches[1].length) { // empty line
if (/^(\s*)/.test(line)) {
// empty line
if (emptyCount > 0) {
this.startBlock('normal', key);
} else {
this.setBlock(key);
}
emptyCount++;
} else if (emptyCount === 0) {
this.setBlock(key);
} else {
this.startBlock('normal', key);
}
} else if (this.isBlock('footnote')) {
var _matches = line.match(/^(\s*)/);
if (_matches[1].length >= this.getBlock()[3][0]) {
this.setBlock(key);
} else {
this.startBlock('normal', key);
}
} else if (this.isBlock('table')) {
if (-1 !== line.indexOf('|')) {
this.setBlock(key);
} else {
this.startBlock('normal', key);
}
} else if (this.isBlock('pre')) {
if (/^\s*$/.test(line)) {
if (emptyCount > 0) {
this.startBlock('normal', key);
} else {
this.setBlock(key);
}
emptyCount++;
} else {
this.startBlock('normal', key);
}
} else if (this.isBlock('quote')) {
if (/^(\s*)/.test(line)) {
// empty line
if (emptyCount > 0) {
this.startBlock('normal', key);
} else {
this.setBlock(key);
}
emptyCount++;
} else if (emptyCount == 0) {
this.setBlock(key);
} else {
this.startBlock('normal', key);
}
} else {
var block = this.getBlock();
if (block === null || block.length === 0 || block[0] !== 'normal') {
this.startBlock('normal', key);
} else {
this.setBlock(key);
}
}
break;
}
}
return this.optimizeBlocks(this.blocks, lines);
}
/**
* @param array blocks
* @param array lines
* @return array
*/
}, {
key: 'optimizeBlocks',
value: function optimizeBlocks(blocks, lines) {
blocks = this.call('beforeOptimizeBlocks', blocks, lines);
blocks.forEach(function (block, key) {
var prevBlock = blocks[key - 1] ? blocks[key - 1] : null;
var nextBlock = blocks[key + 1] ? blocks[key + 1] : null;
var _block2 = _slicedToArray(block, 3);
var type = _block2[0];
var from = _block2[1];
var to = _block2[2];
if ('pre' === type) {
var isEmpty = lines.reduce(function (result, line) {
return line.match(/^\s*$/) && result;
}, true);
if (isEmpty) {
block[0] = type = 'normal';
}
}
if ('normal' === type) {
// combine two blocks
var types = ['list', 'quote'];
if (from === to && lines[from].match(/^\s*$/) && prevBlock && nextBlock) {
if (prevBlock[0] == nextBlock[0] && types.indexOf(prevBlock[0]) !== -1) {
// combine 3 blocks
blocks[key - 1] = [prevBlock[0], prevBlock[1], nextBlock[2], null];
blocks.splice(key, 2);
}
}
}
});
return this.call('afterOptimizeBlocks', blocks, lines);
}
/**
* parseCode
*
* @param array lines
* @param string lang
* @return string
*/
}, {
key: 'parseCode',
value: function parseCode(lines, parts) {
var _parts = _slicedToArray(parts, 2);
var blank = _parts[0];
var lang = _parts[1];
lang = lang.trim();
var count = blank.length;
if (!/^[_a-z0-9-\+\#]+$/i.test(lang)) {
lang = null;
}
lines = lines.slice(1, -1).map(function (line) {
var pattern = new RegExp('/^[ ]{' + count + '}/');
return line.replace(pattern, '');
});
var str = lines.join('\n');
return (/^\s*$/.test(str) ? '' : '<pre><code' + (lang ? ' class="' + lang + '"' : '') + '>' + this.htmlspecialchars(lines.join('\n')) + '</code></pre>'
);
}
/**
* parsePre
*
* @param array lines
* @return string
*/
}, {
key: 'parsePre',
value: function parsePre(lines) {
var _this6 = this;
lines.forEach(function (line, ind) {
lines[ind] = _this6.htmlspecialchars(line.substr(4));
});
var str = lines.join('\n');
return (/^\s*$/.test(str) ? '' : '<pre><code>' + str + '</code></pre>'
);
}
/**
* parseSh
*
* @param array lines
* @param int num
* @return string
*/
}, {
key: 'parseSh',
value: function parseSh(lines, num) {
if (lines[0]) {
var line = this.parseInline(lines[0].trim().replace(/^#+|#+$/g, ''));
return (/^\s*$/.test(line) ? '' : '<h' + num + '>' + line + '</h' + num + '>'
);
} else {
return '';
}
}
/**
* parseMh
*
* @param array lines
* @param int num
* @return string
*/
}, {
key: 'parseMh',
value: function parseMh(lines, num) {
if (lines[0]) {
var line = this.parseInline(lines[0].trim().replace(/^#+|#+$/g, ''));
return (/^\s*$/.test(line) ? '' : '<h' + num + '>' + line + '</h' + num + '>'
);
} else {
return '';
}
}
/**
* parseQuote
*
* @param array lines
* @return string
*/
}, {
key: 'parseQuote',
value: function parseQuote(lines) {
lines.forEach(function (line, key) {
lines[key] = line.replace(/^\s*> ?/, '');
});
var str = lines.join('\n');
return (/^\s*$/.test(str) ? '' : '<blockquote>' + this.parse(str) + '</blockquote>'
);
}
/**
* parseList
*
* @param array lines
* @return string
*/
}, {
key: 'parseList',
value: function parseList(lines) {
var _this7 = this;
var html = '';
var minSpace = 99999;
var rows = [];
// count levels
lines.forEach(function (line, key) {
var matches = line.match(/^(\s*)((?:[0-9a-z]+\.?)|\-|\+|\*)(\s+)(.*)$/);
if (matches) {
var space = matches[1].length;
var type = /[\+\-\*]/.test(matches[2]) ? 'ul' : 'ol';
minSpace = Math.min(space, minSpace);
rows.push([space, type, line, matches[4]]);
} else {
rows.push(line);
}
});
var found = false;
var secondMinSpace = 99999;
rows.forEach(function (row) {
if (Array.isArray(row) && row[0] != minSpace) {
secondMinSpace = Math.min(secondMinSpace, row[0]);
found = true;
}
});
secondMinSpace = found ? 0 : minSpace;
var lastType = '';
var leftLines = [];
rows.forEach(function (row) {
if (Array.isArray(row)) {
var _row = _slicedToArray(row, 4);
var space = _row[0];
var type = _row[1];
var line = _row[2];
var text = _row[3];
if (space !== minSpace) {
var pattern = new RegExp("^\s{" + secondMinSpace + "}");
leftLines.push(line.replace(pattern, ''));
} else {
if (leftLines.length) {
html += "<li>" + _this7.parse(leftLines.join("\n")) + "</li>";
}
if (lastType !== type) {
if (lastType.length) {
html += '</' + lastType + '>';
}
html += '<' + type + '>';
}
leftLines = [text];
lastType = type;
}
} else {
var pattern = new RegExp("^\s{" + secondMinSpace + "}");
leftLines.push(row.replace(pattern, ''));
}
});
if (leftLines.length) {
html += "<li>" + this.parse(leftLines.join("\n")) + ('</li></' + lastType + '>');
}
return html;
}
/**
* @param array lines
* @param array value
* @return string
*/
}, {
key: 'parseTable',
value: function parseTable(lines, value) {
var _this8 = this;
var _value = _slicedToArray(value, 2);
var head = _value[0];
var aligns = _value[1];
var ignore = head ? 1 : 0;
var html = '<table>';
var body = false;
var _loop = function (key) {
var line = lines[key];
if (parseInt(key) === ignore) {
head = false;
body = true;
return 'continue';
}
if (line) {
line = line.trim();
}
if (line[0] === '|') {
line = line.substr(1);
if (line[line.length - 1] === '|') {
line = line.slice(0, -1);
}
}
var rows = line.split('|').map(function (row) {
if (row.match(/^\s+$/)) {
return ' ';
} else {
return row.trim();
}
});
var columns = [];
var last = -1;
rows.forEach(function (row) {
if (row.length > 0) {
last++;
columns[last] = [columns[last] ? columns[last][0] + 1 : 1, row];
} else if (columns[last]) {
columns[last][0]++;
} else {
columns[0] = [1, row];
}
});
if (head === true) {
html += '<thead>';
} else if (body === true) {
html += '<tbody>';
}
html += '<tr>';
columns.forEach(function (column, key) {
var _column = _slicedToArray(column, 2);
var num = _column[0];
var text = _column[1];
var tag = head ? 'th' : 'td';