Monday, March 30, 2009

JavaScript Code Prettifier

Writing technical blog posts about software almost always implies having to include some snippets of code to clarify your ideas, keep your target readers focused and get them to the point quickly. Even sometimes your code just happens to do all the talking. But as you always concentrate on having your thoughts coherent and your code correct you most probably miss the part where your code needs to look nice and easily read. While this can be achieved effortlessly on all current IDEs and text editors which have their syntax-highlighting property prettify your code for you, this needs some effort from you to have them look just as nice and clear on your blog articles. When looking for a tool to help me do that I came across a very nice one, the google-code-prettify project ( A Javascript module and CSS file that allows syntax highlighting of source code snippets in an html page ).

According to their README file you should do the following to have it working:

  1. Download a distribution

  2. Include the script and stylesheets in your document
    (you will need to make sure the css and js file are on your server, and
    adjust the paths in the script and link tag)

    <link href="prettify.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript" src="prettify.js"></script>

  3. Add onload="prettyPrint()" to your
    document's body tag.

  4. Modify the stylesheet to get the coloring you prefer

  5. Put code snippets in <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code>


This would be perfectly applicable if you own your own web server and host your blog there or if you have the blogging host allow you to upload file attachments (as the case here in our blog) for your articles and provide you with their static URLs so you can refer to them in your HTML-format article editor. But be aware that you'll have to change the extension of the file or you might not be able to upload it in most cases. e.g. if you're blogging on our blog then you can refer to this url : which I have uploaded earlier.

If that was not the case and all you've got is the HTML-format editor then you should try this way:

  1. Download a small compressed version of the prettifier.

  2. Copy the CSS text from prettify.css and paste it into a style element in your editor area.

  3. Copy the JavaScript code from prettify.js into and paste it inside a script element.

  4. Put code snippets in <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code>

  5. put prettyPrint() inside a script element at the end of your editor input


Need to see it in action?

You'll get to try it your self.

Type code in the text area to the left, press the prettify button and you'll see the magic.

Type your code here:

Syntax highlighted code:

Generated HTML:

No comments: