forked from potter91dev/markdown-it-custom-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
54 lines (47 loc) · 1.81 KB
/
index.js
File metadata and controls
54 lines (47 loc) · 1.81 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
const markdownIt = require('markdown-it');
const emoji = require('markdown-it-emoji');
const highlightJs = require('markdown-it-highlightjs');
const MarkdownIt = require('markdown-it');
// Plugin to open links in a new tab
function linkNewTabPlugin(md) {
// Remember the original 'link_open' rule
const defaultRender = md.renderer.rules.link_open || function(tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options);
};
md.renderer.rules.link_open = function(tokens, idx, options, env, self) {
// Add target="_blank" attribute
const aIndex = tokens[idx].attrIndex('target');
if (aIndex < 0) {
tokens[idx].attrPush(['target', '_blank']); // add new attribute
} else {
tokens[idx].attrs[aIndex][1] = '_blank'; // replace existing attribute
}
// Call the original 'link_open' rule
return defaultRender(tokens, idx, options, env, self);
};
}
// Plugin to highlight keywords
function keywordHighlightPlugin(md, options) {
options = options || {};
const keywords = options.keywords || [];
const className = options.className || 'highlight';
const defaultRender = md.renderer.rules.text || function(tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options);
};
md.renderer.rules.text = function(tokens, idx, options, env, self) {
let token = tokens[idx];
let content = token.content;
keywords.forEach((keyword) => {
const escapedKeyword = keyword.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const regex = new RegExp(`(${escapedKeyword})`, 'gi');
content = content.replace(regex, `<span class="${className}">$1</span>`);
});
token.content = content;
return defaultRender(tokens, idx, options, env, self);
};
}
// Export the plugins
module.exports = {
linkNewTabPlugin,
keywordHighlightPlugin
};