-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
renderer.js
96 lines (76 loc) · 2.14 KB
/
renderer.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
'use strict';
const marked = require('marked');
const stripIndent = require('strip-indent');
const { stripHTML, highlight, slugize } = require('hexo-util');
const MarkedRenderer = marked.Renderer;
function Renderer() {
MarkedRenderer.apply(this);
this._headingId = {};
}
require('util').inherits(Renderer, MarkedRenderer);
// Add id attribute to headings
Renderer.prototype.heading = function(text, level) {
const transformOption = this.options.modifyAnchors;
let id = anchorId(stripHTML(text), transformOption);
const headingId = this._headingId;
// Add a number after id if repeated
if (headingId[id]) {
id += `-${headingId[id]++}`;
} else {
headingId[id] = 1;
}
// add headerlink
return `<h${level} id="${id}"><a href="#${id}" class="headerlink" title="${stripHTML(text)}"></a>${text}</h${level}>`;
};
function anchorId(str, transformOption) {
return slugize(str.trim(), {transform: transformOption});
}
// Support AutoLink option
Renderer.prototype.link = function(href, title, text) {
if (this.options.sanitize) {
let prot;
try {
prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.startsWith('javascript:') || prot.startsWith('vbscript:') || prot.startsWith('data:')) {
return '';
}
}
if (!this.options.autolink && href === text && title == null) {
return href;
}
let out = `<a href="${href}"`;
if (title) {
out += ` title="${title}"`;
}
out += `>${text}</a>`;
return out;
};
// Support Basic Description Lists
Renderer.prototype.paragraph = text => {
const dlTest = /(?:^|\s)(\S.+)<br>:\s+(\S.+)/;
const dl = '<dl><dt>$1</dt><dd>$2</dd></dl>';
if (dlTest.test(text)) {
return text.replace(dlTest, dl);
}
return `<p>${text}</p>\n`;
};
marked.setOptions({
langPrefix: '',
highlight(code, lang) {
return highlight(stripIndent(code), {
lang,
gutter: false,
wrap: false
});
}
});
module.exports = function(data, options) {
return marked(data.text, Object.assign({
renderer: new Renderer()
}, this.config.marked, options));
};