Pages

Friday, October 14, 2011

1

Publishing syntax highlighted code in Blogger

This was tougher than I first thought. I thought that I'll just install SyntaxHighlighter, and that's it. But not quite.

First I installed SyntaxHighlighter 2.x, according to some instructions on the net. It had some problems, so after a few days, I switched to newest version, 3.0.83.

Publishing code between <pre> tags is a bit problematic alltogether. One must escape some characters, like > and < to &gt; and &lt;, to allow for example html to be shown. So there's always this extra step.

The most problematic thing with SyntaxHighlighter is that it changed left intendation spaces to non breaking spaces. That is mainly cosmetic, but can result in nasty looking &#160;:s in template, although harmless. As some sort of a perfectionist I could not let this be.

So my final (at least at this point in time) solution, which I came up yesterday, is to use pastebin.com to host those (longer) code snippets, that are supposed to be copied by user. Other codes may still be shown by SyntaxHighlighter. I styled SyntaxHighlighter and Pastebin codes to look similar.

Example, first pastebin:

Data provided by Pastebin.com - Download Raw

Then SyntaxHighlighter:
<script type='text/javascript'>
//<![CDATA[
// make pastebin.com raw links open in target="_blank"
  var clss = document.getElementsByClassName("embedFooter");
  for (var x=0 ; x < clss.length; x++ )
  {
    var child = clss[x].firstChild;
    while(child) {
      if(child.nodeType == 1 && child.tagName.toLowerCase() == 'a')
        child.target="_blank";
      child = child.nextSibling;
    }
  }
//]]>
</script>
Internet Explorer needed some styling for its own, that one I figured out this morning, there was for example a persistent vertical scrollbar on SyntaxHighligter code snippets. But I got those sorted out. Finally I coded the above script to make the "Download Raw" link open the code in a new window.

The best way for user to copy pastebin codes is to click the Download Raw link, and to copy SyntaxHighlighter codes is to doubleclick the code. Of course mouse selection and copy can be used, but depending on browser that might also copy the line numbers. Hopefully my blog's readers are able to figure these out.

1 comments:

Blogger said... [reply]

GitHubs and Pastebins both are definitely overkill for such a simple task ^:(

Today I was looking for a simpler solution:

http://crocode.blogspot.com/2012/08/blogspot-syntax-highlighting-issue.html

Post a Comment

Related Posts Plugin for WordPress, Blogger...
See the hack
for this dynamic
views icon: