https://github.com/chjj/marked#highlight
I'd like to use prism together with marked, to render markdown in the browser. Any ideas?
It looks like it is, as long as the correct grammars are loaded first.
marked.setOptions({
highlight: function (code, lang) {
return Prism.highlight(code, Prism.languages[lang], lang);
}
});
If someone writes markdown code block without specifying the language, it fails.
some unknown code here
Now I get rid of it by fallback to markup, any better ideas?
function (code, lang) {
return prism.highlight(code, prism.languages[lang || 'markup'])
}
BTW, I found highlight.js provides an "auto" method to predict the language.
Prism has no way to autodetect the language currently. And it's not planned afaik.
I guess you could also fallback to doing no highlighting whatsoever when the language is not specified.
I am using the marked options key highlight function and it does not add the appropriate class to the <pre> tags for code blocks. <code> tags have the appropriate class, but not the <pre> tags that wrap them.
This is a problem for Prism because it claims that classes with no <pre> tag class is fine. From the Prism website:
If you use that pattern, the <pre> will automatically get the language-xxxx class (if it doesn鈥檛 already have it) and will be styled as a code block.
This is not occurring when I'm using Prism with marked. I am defining the behavior inside a React component .tsx file. Here is my code:
return (
<Layout title={title}>
<div
className={postWrapper}
dangerouslySetInnerHTML={{
__html: marked(md, {
highlight: (code, lang) => {
// @ts-ignore
return window.Prism.highlight(
code,
// @ts-ignore
window.Prism.languages[lang],
'typescript'
)
}
})
}}
></div>
</Layout>
marked.setOptions({
highlight: function(code, lang) {
if (prism.languages[lang]) {
return prism.highlight(code, prism.languages[lang], lang);
} else {
return code;
}
}
});
@chiefgunner This highlight function is dangerous. Prism will always return HTML source code meaning that all special HTML characters (<, &) will be escaped. In your case, this function can give you a good case of XSS depending on whether Prism supports a specific language.
You can use Prism.util.encode(someString) to escape all special HTML characters.
Most helpful comment
I am using the
markedoptions keyhighlightfunction and it does not add the appropriate class to the<pre>tags for code blocks.<code>tags have the appropriate class, but not the<pre>tags that wrap them.This is a problem for Prism because it claims that classes with no
<pre>tag class is fine. From the Prism website:This is not occurring when I'm using Prism with
marked. I am defining the behavior inside a React component.tsxfile. Here is my code: