syntax-highlightingsyntaxhighlighter

SyntaxHighlighter gets parsed incorrectly


My SyntaxHighlighter gets parsed incorrectly, inserting code blocks with <pre class="brush: lang">...</pre> into Markdown, for instance:

Case 1: remove </body>

`</body>` parse as ``

Case 2: incorrectly pairing

<pre class="brush: java">
private class MaxPropComparator implements Comparator<message> {
    ...
}
</pre>

is parsed as (add </message>):

<pre class="brush: java">
private class MaxPropComparator implements Comparator<message> {
    ...
}
</message></pre>

Case 3: embedded code blocks

<pre class="brush: xml; smart-tabs: false">
<pre class="brush: js; highlight: [2, 4, 6]">
...
</pre>
</pre>

is parsed as:

<pre class="brush: xml; smart-tabs: false">
</pre><pre class="brush: js; highlight: [2, 4, 6]">
...
</pre>

therefore display as:

enter image description here

Case 4: and so on

# messages: event-type org-node (loc-x,loc-y) (anchor-x,anchor-y) r=<core> a=<availability> ttl size [node-snd ( loc-x loc-y ) [node-rcv (     loc-x loc-y)]]

is parsed as (add </availability></core>):

# messages: event-type org-node (loc-x,loc-y) (anchor-x,anchor-y) r=<core> a=<availability> ttl size [node-snd ( loc-x loc-y ) [node-rcv (     loc-x loc-y)]]
</availability></core>

Solution

  • The reason:

    PROBLEMS: Major issue with this method is that all left angle brackets must be HTML escaped, eg all < must be replaced with &lt; This will ensure correct rendering.


    My soluation: shift SyntaxHighlighter to Google Code Prettify and make the previous codes compatiable with Google Code Prettify. Here is what I do:

    <script>
    jQuery(document).ready(function(){
        jQuery('pre').each(function(){
            var el = jQuery(this).find('code');
            var code_block = el.html(); // remove the pairwise tag of <code></code>
            var lang = el.attr('class');
    
            if (el.length > 0) { // <pre>...</pre> with <code>...</code> inside
                if (lang) {
                    jQuery(this).addClass('prettyprint linenums lang-' + lang).html(code_block);
                } else {
                    jQuery(this).addClass('prettyprint linenums').html(code_block);
                }
            } else { // <pre>...</pre> without <code>...</code> inside
                jQuery(this).removeClass().addClass('prettyprint linenums'); // take over SyntaxHighlighter
            }
        });
    });
    </script>