Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Markdown syntax highlighting in Javascript

I am trying to get the rainbow syntax highlighting library to work with the marked markdown rendering engine. The marked documentation states that a syntax highlighter is supported through the following configuration option:

marked.setOptions({
  highlight: function(code, lang) {
    return highlighter.javascript(code);
  }
});

The rainbow source code indicates that passing in a string to highlight is supported via the following syntax:

Rainbow.color(code, lang, success);

I'm a bit at a loss as to how to put the two together. Specifically, success is a callback that will be called asynchronously, and I can't simply return the value from the Rainbow.color code inside the highlight callback. How would this be accomplished?

like image 306
user2398029 Avatar asked Dec 12 '22 17:12

user2398029


2 Answers

Author of marked here. I addressed this a while ago on the issue tracker: https://github.com/chjj/marked/issues/47

It's more than possible to use an asynchronous highlighter with marked. You'll just have to iterate over the tokens the lexer spits out.

Example here: https://github.com/chjj/marked/issues/47#issuecomment-5297067 (Keep in mind this is an example. You'll have to modify it a bit.)

I might just implement this natively in marked using the method in the link above. It will be a performance hit to the people using async highlighters, but if you need an async highlighter, that means the highlighter is doing some kind of IO and you're already taking a performance hit.

like image 171
chjj Avatar answered Dec 30 '22 01:12

chjj


You could try using another highlighting library, such as highlight.js - It has synchronous highlighting methods (hljs.highlight(lang, code).value and hljs.highlightAuto(code).value) that you can use in the browser like this:

marked.setOptions({
  highlight: function(code) {
    return hljs.highlightAuto(code).value;
  }
});

Here's a working JsFiddle example.

like image 36
Daiz Avatar answered Dec 30 '22 02:12

Daiz