Skip to content

Instantly share code, notes, and snippets.

@tajpure
Created August 14, 2016 10:44
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Support katex for marked.
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})
@olivren
Copy link

olivren commented Mar 5, 2022

Hi!

This bridge code is working well, thanks a lot.
I'd like to use the code in this gist in a project. Could you apply a license on it please? Just commenting "this is MIT" or whatever is enough.
Thanks again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment