-
-
Save jolks/7a6af0048cd627b9e330f332a72283bb to your computer and use it in GitHub Desktop.
Support katex for marked.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const renderer = new marked.Renderer() | |
let originParagraph = renderer.paragraph.bind(renderer) | |
renderer.paragraph = (text) => { | |
const blockRegex = /\$\$[^\$]*\$\$/g | |
const inlineRegex = /\$[^\$]*\$/g | |
let blockExprArray = text.match(blockRegex) | |
let inlineExprArray = text.match(inlineRegex) | |
for (let i in blockExprArray) { | |
const expr = blockExprArray[i] | |
const result = renderMathsExpression(expr) | |
text = text.replace(expr, result) | |
} | |
for (let i in inlineExprArray) { | |
const expr = inlineExprArray[i] | |
const result = renderMathsExpression(expr) | |
text = text.replace(expr, result) | |
} | |
return originParagraph(text) | |
} | |
function renderMathsExpression (expr) { | |
if (expr[0] === '$' && expr[expr.length - 1] === '$') { | |
let displayStyle = false | |
expr = expr.substr(1, expr.length - 2) | |
if (expr[0] === '$' && expr[expr.length - 1] === '$') { | |
displayStyle = true | |
expr = expr.substr(1, expr.length - 2) | |
} | |
let html = null | |
try { | |
html = katex.renderToString(expr) | |
} catch (e) { | |
console.err(e) | |
} | |
if (displayStyle && html) { | |
html = html.replace(/class="katex"/g, 'class="katex katex-block" style="display: block;"') | |
} | |
return html | |
} else { | |
return null | |
} | |
} | |
marked.setOptions({renderer: renderer}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment