Skip to content

Commit 5411059

Browse files
committed
feature: add support for highlighting syntax in Markdown previews
1 parent da17ee9 commit 5411059

File tree

3 files changed

+2800
-3
lines changed

3 files changed

+2800
-3
lines changed

extension.js

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/* eslint-disable global-require */
2+
const packageJson = require('./package.json');
3+
4+
const get = (obj, path, defaultValue) => {
5+
const lookup = !(obj === null || obj === undefined) ? obj[path] : undefined;
6+
if (lookup !== undefined) {
7+
return lookup;
8+
}
9+
const result = String.prototype.split
10+
.call(path, /[,.[\]]+?/)
11+
.filter(Boolean)
12+
.reduce(
13+
(res, key) => (!(res === null || res === undefined) ? res[key] : undefined),
14+
obj
15+
);
16+
return result === undefined || result === obj ? defaultValue : result;
17+
};
18+
19+
const languageId = get(packageJson, 'contributes.languages[0].id', 'textproto').toLowerCase();
20+
const aliases = []
21+
.concat(get(packageJson, 'contributes.languages[0].aliases'))
22+
.map((x) => x.toLowerCase())
23+
.filter((x) => x !== languageId);
24+
const languageTest = new RegExp(`(${languageId}|${aliases.join('|')})`, 'i');
25+
26+
/** @type LanguageFn */
27+
const textproto = (hljs) => {
28+
/** @type Mode */
29+
const HERE_DOCS = {
30+
begin: /<<\s*(?=[A-Z_a-z]+)/,
31+
starts: {
32+
contains: [
33+
hljs.END_SAME_AS_BEGIN({
34+
begin: /([A-Z_a-z]+)/,
35+
end: /([A-Z_a-z]+)/,
36+
className: 'string',
37+
}),
38+
],
39+
},
40+
};
41+
return {
42+
name: 'Protocol Buffer Text Format',
43+
aliases,
44+
contains: [
45+
hljs.QUOTE_STRING_MODE,
46+
hljs.NUMBER_MODE,
47+
hljs.HASH_COMMENT_MODE,
48+
{
49+
className: 'object',
50+
begin: /{/,
51+
end: /}/,
52+
contains: [
53+
hljs.QUOTE_STRING_MODE,
54+
hljs.NUMBER_MODE,
55+
hljs.HASH_COMMENT_MODE,
56+
HERE_DOCS,
57+
],
58+
},
59+
HERE_DOCS,
60+
],
61+
};
62+
};
63+
64+
module.exports.activate = () => ({
65+
extendMarkdownIt(md) {
66+
const hljs = require('highlight.js/lib/core');
67+
const { highlight } = md.options;
68+
md.use(require('markdown-it-highlightjs/core'), {
69+
hljs,
70+
register: {
71+
textproto,
72+
},
73+
});
74+
// eslint-disable-next-line no-param-reassign
75+
md.options.highlight = (code, lang) => {
76+
if (lang && lang.match(languageTest)) {
77+
try {
78+
return `<div>${hljs.highlight(lang, code, true).value}</div>`;
79+
} catch (error) {
80+
/* empty */
81+
}
82+
}
83+
return highlight(code, lang);
84+
};
85+
return md;
86+
},
87+
});

0 commit comments

Comments
 (0)