Skip to content

Instantly share code, notes, and snippets.

@jolks
Forked from tajpure/marked-katex.js
Created January 14, 2020 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jolks/7a6af0048cd627b9e330f332a72283bb to your computer and use it in GitHub Desktop.
Save jolks/7a6af0048cd627b9e330f332a72283bb to your computer and use it in GitHub Desktop.
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})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment