Friday, March 26, 2010

setting up blogger to format source code

I want to be able to post source code with basic syntax highlighting.

After some searching I found a JavaScript module that would do it using markup. After more searching I found a Google hosted copy of the script to use on blogger, in use on JQuery HowTo.

The software used to do this is google-code-prettify: syntax highlighting of code snippets in a web page. It keeps it simple and does what it says it does well.

To install the functionality I added the following block of code to a Blogger layout block after the Blog Posts layout block.

<!--
from: http://jquery-howto.blogspot.com/2009/02/new-code-highlighter-for-bloggercom.html
-->
<script src="http://www.gstatic.com/codesite/ph/2429932258724909799/js/prettify/prettify.js">
</script>
<script type="text/javascript">
prettyPrint();
</script>

<style type="text/css">

/* Pretty printing styles. Used with prettify.js. */

.str { color: #080; }
.kwd { color: #008; }
.com { color: #800; }
.typ { color: #606; }
.lit { color: #066; }
.pun { color: #660; }
.pln { color: #000; }
.tag { color: #008; }
.atn { color: #606; }
.atv { color: #080; }
.dec { color: #606; }
pre.prettyprint { padding: 2px; border: 1px solid #888; overflow:auto; }

@media print {
  .str { color: #060; }
  .kwd { color: #006; font-weight: bold; }
  .com { color: #600; font-style: italic; }
  .typ { color: #404; font-weight: bold; }
  .lit { color: #044; }
  .pun { color: #440; }
  .pln { color: #000; }
  .tag { color: #006; font-weight: bold; }
  .atn { color: #404; }
  .atv { color: #060; }
}
</style>

To use it in a post just involves wrapping the code in <pre class="prettyprint"> and </pre>, or <code class="prettyprint"> and </code>, and ensuring that the ampersands and angle brackets are properly escaped using &amp;, &lt;, and &gt;.

Update: Added automatic scroll bars for wide lines.

2 comments:

  1. Please explain how to add this code to the Blogger layout block

    ReplyDelete
  2. Customize -> Add a Gadget
    choose HTML/JavaScript
    paste the content into the box, leave the title blank
    Save

    It should work

    ReplyDelete