llm-bot/markdown.ts

57 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

2023-12-24 11:11:19 +00:00
import * as marked from "npm:marked";
const inlineRule = /^\${1,2}([^$\n]+)\${1,2}/;
const blockRule = /^\${1,3}\n([^$\n]+)\n\${1,3}/;
const inlineLatexExtension = {
name: "inlineKatex",
level: "inline",
start(src) {
const match = src.match(inlineRule);
if (!match) return;
return match.index;
},
tokenizer(src, tokens) {
const match = src.match(inlineRule);
if (match) {
return {
type: 'inlineKatex',
raw: match[0],
text: match[1].trim(),
};
}
},
renderer(token) {
const text = token.text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
return `<span data-mx-maths="${text}"><code>${text}</code></span>`;
},
}
const blockLatexExtension = {
name: "blockLatex",
level: "inline",
start(src) {
const match = src.match(blockRule);
if (!match) return;
return match.index;
},
tokenizer(src, tokens) {
const match = src.match(blockRule);
if (match) {
return {
type: 'blockKatex',
raw: match[0],
text: match[1].trim(),
};
}
},
renderer(token) {
const text = token.text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
return `<p><span data-mx-maths="${text}"><code>${text}</code></span></p>`;
},
}
marked.use({ extensions: [inlineLatexExtension, blockLatexExtension] });
export default marked;