-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
backtick_code_block.js
70 lines (54 loc) · 2.05 KB
/
backtick_code_block.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
'use strict';
const stripIndent = require('strip-indent');
const { highlight } = require('hexo-util');
const rBacktick = /^((?:[^\S\r\n]*>){0,3}[^\S\r\n]*)(`{3,}|~{3,}) *(.*) *\n([\s\S]+?)\s*\2(\n+|$)/gm;
const rAllOptions = /([^\s]+)\s+(.+?)\s+(https?:\/\/\S+|\/\S+)\s*(.+)?/;
const rLangCaption = /([^\s]+)\s*(.+)?/;
function backtickCodeBlock(data) {
const config = this.config.highlight || {};
if (!config.enable) return;
data.content = data.content.replace(rBacktick, ($0, start, $2, _args, content, end) => {
const args = _args.split('=').shift();
const options = {
hljs: config.hljs,
autoDetect: config.auto_detect,
gutter: config.line_number,
tab: config.tab_replace,
wrap: config.wrap
};
if (options.gutter) {
config.first_line_number = config.first_line_number || 'always1';
if (config.first_line_number === 'inline') {
// setup line number by inline
_args = _args.replace('=+', '=');
options.gutter = _args.includes('=');
// setup fiestLineNumber;
options.firstLine = options.gutter ? _args.split('=')[1] || 1 : 0;
}
}
if (args) {
const match = rAllOptions.exec(args) || rLangCaption.exec(args);
if (match) {
options.lang = match[1];
if (match[2]) {
options.caption = `<span>${match[2]}</span>`;
if (match[3]) {
options.caption += `<a href="${match[3]}">${match[4] ? match[4] : 'link'}</a>`;
}
}
}
}
// PR #3765
if (start.includes('>')) {
const depth = start.split('>').length - 1;
const regexp = new RegExp(`^([^\\S\\r\\n]*>){0,${depth}}([^\\S\\r\\n]|$)`, 'mg');
const paddingOnEnd = ' '; // complement uncaptured whitespaces at last line
content = (content + paddingOnEnd).replace(regexp, '').replace(/\n$/, '');
}
content = highlight(stripIndent(content), options)
.replace(/{/g, '{')
.replace(/}/g, '}');
return `${start}<escape>${content}</escape>${end}`;
});
}
module.exports = backtickCodeBlock;