43 lines
1.7 KiB
TypeScript
43 lines
1.7 KiB
TypeScript
|
|
import markdownit from 'markdown-it';
|
|
import hljs from 'highlight.js'; // https://highlightjs.org
|
|
import katexPlugin from '@iktakahiro/markdown-it-katex';
|
|
const stringToUtf8Hex = function(str:string){
|
|
let utf8Hex = '';
|
|
for (let i = 0; i < str.length; i++) {
|
|
let code = str.charCodeAt(i);
|
|
if (code < 128) {
|
|
utf8Hex += code.toString(16).padStart(2, '0');
|
|
} else if (code < 2048) {
|
|
utf8Hex += (192 | (code >> 6)).toString(16).padStart(2, '0');
|
|
utf8Hex += (128 | (code & 63)).toString(16).padStart(2, '0');
|
|
} else {
|
|
utf8Hex += (224 | (code >> 12)).toString(16).padStart(2, '0');
|
|
utf8Hex += (128 | ((code >> 6) & 63)).toString(16).padStart(2, '0');
|
|
utf8Hex += (128 | (code & 63)).toString(16).padStart(2, '0');
|
|
}
|
|
}
|
|
return utf8Hex;
|
|
}
|
|
const codeTool = (text: string) => `<svg id="copy" class="icon" aria-hidden="true" style="font-size:16px;display: inline-block;color:#fff;position:absolute;right:8px;top:6px;cursor:pointer;" data-copy="${text}"><use xlink:href="#gt-line-copy"></use></svg>`;
|
|
|
|
const md = markdownit({
|
|
html: true,
|
|
linkfy: true,
|
|
highlight: function (str: string, lang: string) {
|
|
const baseText = stringToUtf8Hex(str);
|
|
if (lang && hljs.getLanguage(lang)) {
|
|
try {
|
|
return '<pre><code class="hljs">' +
|
|
hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
|
|
'</code>' + codeTool(baseText) + '</pre>';
|
|
} catch (__) { }
|
|
}
|
|
return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code>' + codeTool(baseText) + '</pre>';
|
|
}
|
|
});
|
|
|
|
md.use(katexPlugin);
|
|
|
|
export default md;
|