-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
106 lines (88 loc) · 3.02 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
'use strict'
const cheerio = require('cheerio');
const PluginError = require('plugin-error');
const through = require('through2');
const path = require('path');
const fs = require('fs');
// Use when developing locally:
// const langPath = "node_modules/prismjs/";
const langPath = "../prismjs/";
const normalizedPath = path.join(__dirname, langPath);
function getAllLanguages() {
let languagesToLoad = [];
fs.readdirSync(normalizedPath + "components/").forEach( file => {
if (/^.+\.min\.(js)$/i.test(file)) {
let languageName = file.replace('prism-', '').replace('.min.js', '');
if (languageName !== 'core'){
languagesToLoad.push(languageName);
}
}
});
return languagesToLoad;
}
const Prism = require(`${normalizedPath}/components/prism-core.js`);
const loadLanguages = require(`${normalizedPath}/components/index.js`);
loadLanguages(getAllLanguages());
const packageName = require('./package.json').name;
const defaultConfig = {
selector: 'pre code',
cheerio: {
decodeEntities: false,
}
}
const entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
}
function escapeHTML(HTMLString) {
return String(HTMLString).replace(/[&<>"'`=\/]/g, s => entityMap[s]);
}
function highlight(text, config) {
const $ = cheerio.load(text, config.cheerio);
$(config.selector)
.each((i, el) => {
const langPrefixRegex = /\blang(?:uage)?-([\w-]+)\b/i;
const blockClasses = $(el).attr('class') ? $(el).attr('class').split(' ') : [];
let hasLangClass = false;
let language = '';
for (let i = 0; i < blockClasses.length; i++) {
let match = blockClasses[i].match(langPrefixRegex);
if (match) {
hasLangClass = true;
language = match[1].toLowerCase();
}
}
const prismLangObj = Prism.languages[language];
if(hasLangClass && language && prismLangObj) {
$(el).text(Prism.highlight($(el).html(), prismLangObj)).addClass('prism');
} else {
$(el).text(escapeHTML($(el).text())).addClass('no-prism');
}
});
return $.html() || text;
}
module.exports = (options) => {
const config = Object.assign({}, defaultConfig, options)
return through.obj(function (file, encoding, done) {
if (file.isNull()) {
return done(null, file);
}
if (file.isStream()) {
this.emit('error', new PluginError(packageName, 'Streams not supported!'));
return done();
}
try {
const text = file.contents.toString();
file.contents = Buffer.from(highlight(text, config));
} catch (error) {
this.emit('error', new PluginError(packageName, error));
}
done(null, file);
})
}