Home arrow JavaScript arrow More of the Best Javascript Syntax Highlighters
JAVASCRIPT

More of the Best Javascript Syntax Highlighters


JavaScript syntax highlighters are a relatively new breed of tool that let you beautify code fragments included in (X)HTML documents, making them look more pleasant and readable to the human eye. While similar results can be achieved by means of plain CSS, the truth is that third-party highlighting libraries can perform the whole beautifying process with minimal set-up. In this article, we continue our look into the best code highlighters and show how to implement them.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 1
July 31, 2011

print this article
SEARCH DEVARTICLES

JavaScript syntax highlighters are a relatively new breed of tool that let you beautify code fragments included in (X)HTML documents, making them look more pleasant and readable to the human eye. While similar results can be achieved by means of plain CSS, the truth is that third-party highlighting libraries can perform the whole beautifying process with minimal set-up. In this article, we continue our look into the best code highlighters and show how to implement them.

If you had the opportunity to look at the introductory part of this tutorial (http://www.devarticles.com/c/a/JavaScript/Popular-JavaScript-Syntax-Highlighters/), you should have a pretty clear idea of the advantages offered by some of the most popular JavaScript syntax highlighters available nowadays, as I took an in-depth look at two important contenders in the field: namely the already classic SyntaxHighlighter (http://alexgorbatchev.com/SyntaxHighlighter), and SHJS (http://shjs.sourceforge.net).

To be frank, both libraries do a great job when it comes to highlighting online code snippets, even though the former comes bundled with a few additional goodies, such as line numbers, a gutter, and so forth, which have turned it into the preferred choice of many bloggers and ezines out there.

In this article I’ll be showcasing another couple of players, whose names may sound familiar to you: Highlight.js and Google Code Prettify, two feature-rich libraries that are a snap to setup and use.

Highlight.js

The next player that I plan to analyze in this overview of JavaScript syntax highlighters is Highlight.js (http://softwaremaniacs.org/soft/highlight/en). Similar to other competitors previously discussed, the library offers support for over 41 different languages and it’s very easy to configure and utilize. Simply put, all that you’ll need to do to get the program up and running is to include its main file, called “highlight.pack.js”, then the CSS theme of your choice, and finally call its “initHighlightingOnLoad()” method, into your web page, in order to highlight the target code samples.  

For you to better understand how to work with Highlight.js, below I set up a brand new example, which uses the package to beautify the same PHP fragment that you saw in the preceding tutorial. Have a look at it:

<!doctype html>

<html>

<head>

<meta charset=utf-8>

<title>Using highlight.js Syntax highlighter (default theme)</title>

<!-- Include the JavaScript dependencies -->

<script src="highlight/highlight.pack.js"></script>

<!-- Include the default styles -->

<link rel="stylesheet" href="highlight/styles/default.css">

<style type="text/css">

body {

    padding: 0;

    margin: 0;

    background: #fff;

    font: 1em Arial, Helvetica, sans-serif;

    color: #000;

}

#wrapper {

    width: 800px;

    margin: 0 auto;

}

</style>

</head>

<body>

    <div id="wrapper">

        <header>

            <h1>Using highlight.js Syntax highlighter (default theme)</h1>

                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>

        </header>

        <section id="code-section">

            <header>

                <h2>Sample code section</h2>

            </header>

            <pre>

                <code>

    &lt;?php

 

    namespace SampleApp\Common; 

    class ServiceLocator implements RegistrableInterface

    {

        protected $_resources = array(); 

        /**

         * Set the specified resource

         */

        public function set($key, AbstractResource $resource)

        {

            if (!isset($this-&gt;_resources[$key])) {

                $this-&gt;_resources[$key] = $resource;

            }

            return $this;           

        } 

        /**

         * Get the specified resource

         */

        public function get($key)

        {

            if (isset($this-&gt;_resources[$key])) {

                return $this-&gt;_resources[$key];

            }

            throw new \InvalidArgumentException('The requested resource does not exist.');

        } 

        /**

         * Remove the specified resource

         */

        public function remove($key)

        {

            if (isset($this-&gt;_resources[$key])) {

                unset($this-&gt;_resources[$key]);

                return $this;

            }

            throw new \InvalidArgumentException('The resource to be removed does not exist.');

        }

         

        /**

         * Check if the specified resource exists

         */

        public function exists($key)

        {

            return isset($this-&gt;_resources[$key]);

        }     

    }

                </code>

            </pre>

        </section>

        <footer>

            <header>

                <h2>Footer section</h2>

            </header>

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>

        </footer>

    </div>

    <script>

    // highlight the code section

    hljs.initHighlightingOnLoad();

    </script>   

</body>

</html>

Not that I want to sound like I’m marketing the library, but as you can see above, putting Highlight.js to work is an extremely simple process, reduced to wrapping the target code sample inside a couple of <pre><code> elements and invoking the aforementioned “initHighlightingOnLoad()” method after the web page has been loaded.

In addition, you may have noticed that I decided to use the library’s default CSS theme. Well, if you try out the previous example with the theme in question, here’s how the PHP fragment will look after being parsed by Highlight.js:   

That worked like a charm. And most importantly, the whole highlighting process didn’t require you to deal with complicated settings or anything weird. Don’t let this simplicity fool you, though, as the library’s flexibility will permit you to change different themes in a jiffy. Want to see a concrete example of this? Then look at the example below, which puts the library into action, but this time with its “Dark theme”:

<!doctype html>

<html>

<head>

<meta charset=utf-8>

<title>Using highlight.js Syntax highlighter (Dark theme)</title>

<!-- Include the JavaScript dependencies -->

<script src="highlight/highlight.pack.js"></script>

<!-- Include the default styles -->

<link rel="stylesheet" href="highlight/styles/dark.css">

<style type="text/css">

body {

    padding: 0;

    margin: 0;

    background: #fff;

    font: 1em Arial, Helvetica, sans-serif;

    color: #000;

}

#wrapper {

    width: 800px;

    margin: 0 auto;

}

</style>

</head>

<body>

    <div id="wrapper">

        <header>

            <h1>Using highlight.js Syntax highlighter (Dark theme)</h1>

                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>

        </header>

        <section id="code-section">

            <header>

                <h2>Sample code section</h2>

            </header>

            <pre>

                <code>

    &lt;?php   

    namespace SampleApp\Common;

    class ServiceLocator implements RegistrableInterface

    {

        protected $_resources = array(); 

        /**

         * Set the specified resource

         */

        public function set($key, AbstractResource $resource)

        {

            if (!isset($this-&gt;_resources[$key])) {

                $this-&gt;_resources[$key] = $resource;

            }

            return $this;          

        }

        /**

         * Get the specified resource

         */

        public function get($key)

        {

            if (isset($this-&gt;_resources[$key])) {

                return $this-&gt;_resources[$key];

            }

            throw new \InvalidArgumentException('The requested resource does not exist.');

        }  

        /**

         * Remove the specified resource

         */

        public function remove($key)

        {

            if (isset($this-&gt;_resources[$key])) {

                unset($this-&gt;_resources[$key]);

                return $this;

            }

            throw new \InvalidArgumentException('The resource to be removed does not exist.');

        }         

        /**

         * Check if the specified resource exists

         */

        public function exists($key)

        {

            return isset($this-&gt;_resources[$key]);

        }     

    }

                </code>

            </pre>

        </section>

        <footer>

            <header>

                <h2>Footer section</h2>

            </header>

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>

        </footer>

    </div>

    <script>

    // highlight the code section

    hljs.initHighlightingOnLoad();

    </script>   

</body>  

</html>

 

As shown above, now the library makes use of a different theme (notice the inclusion of the “dark.css” file) for highlighting the sample PHP snippet. This subtle change generates the following output when the pertaining web page is rendered on the browser:

This shows in a nutshell that not only does Highlight.js perform superbly when it comes to polishing the visual presentation of code samples, but it has a truly flat learning curve, something that lets you focus your attention on your real work, instead of having to deal with twisted and annoying configuration options.

To make long things short: if you’re looking for a highlighting package that offers a proper balance between functionality and ease of use, Highlight.js is definitively a choice that deserves a close look.

Google Code Prettify

Not surprisingly, the next contender in this review is Google Code Prettify (http://code.google.com/p/google-code-prettify) the popular syntax highlighting library used across code.google.com and stackoverflow.com. As with other projects powered by the search company, Google Code Prettify is a breeze to use and comes bundled with some engaging features, such as support for multiple languages, CSS themes and line numbering.

Similar to other libraries previously covered, Google Code Prettify requires only two dependencies to work as expected: its main JavaScript file along with the mentioned CSS themes.

Of course, the most effective way to see the package in action is through a concrete example. Based on this idea, I created a simple example, which shows how to use the library with the previous PHP source snippet. Check it out:  

<!doctype html>

<html>

<head>

<meta charset=utf-8>

<title>Using Google Code Prettify Syntax highlighter</title>

<!-- Include the JavaScript dependencies -->

<script src="google-code-prettify/prettify.js"></script>

<!-- Include the default styles -->

<link href="google-code-prettify/prettify.css" type="text/css" rel="stylesheet" />

<style type="text/css">

body {

    padding: 0;

    margin: 0;

    background: #fff;

    font: 1em Arial, Helvetica, sans-serif;

    color: #000;

}

#wrapper {

    width: 800px;

    margin: 0 auto;

}

</style>

</head>

<body>

    <div id="wrapper">

        <header>

            <h1>Using Google Code Prettify Syntax highlighter</h1>

                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>

        </header>

        <section id="code-section">

            <header>

                <h2>Sample code section</h2>

            </header>

            <pre class="prettyprint">

                <code>

    &lt;?php

 

    namespace SampleApp\Common; 
    class ServiceLocator implements RegistrableInterface

    {

        protected $_resources = array(); 

         /**

         * Set the specified resource

         */

        public function set($key, AbstractResource $resource)

        {

            if (!isset($this-&gt;_resources[$key])) {

                $this-&gt;_resources[$key] = $resource;

            }

            return $this;          

        } 

         /**

         * Get the specified resource

         */

        public function get($key)

        {

            if (isset($this-&gt;_resources[$key])) {

                return $this-&gt;_resources[$key];

            }

            throw new \InvalidArgumentException('The requested resource does not exist.');

        } 

         /**

         * Remove the specified resource

         */

        public function remove($key)

        {

            if (isset($this-&gt;_resources[$key])) {

                unset($this-&gt;_resources[$key]);

                return $this;

            }

            throw new \InvalidArgumentException('The resource to be removed does not exist.');

        }

         

        /**

         * Check if the specified resource exists

         */

        public function exists($key)

        {

            return isset($this-&gt;_resources[$key]);

        }     

    }

                </code>

            </pre>

        </section>

        <footer>

            <header>

                <h2>Footer section</h2>

            </header>

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>

        </footer>

    </div>

    <script>

    // highlight the code section

    prettyPrint();

    </script>   

</body>

</html>

Although the above example is pretty self-explanatory, there’s a couple of things worth noting: first and foremost, the sample PHP fragment has been placed within the classic <pre><code> tags, while the first element has been assigned a class called “prettyprint”. Last but not least, the whole highlighting process is fired up by invoking a single method, named, “prettyPrint()”.

Now, if you give the previous example a try using your own browser, you should get a result similar to the one shown by the following snapshot:

At this point, it’s clear to see that Google Code Prettify is a snap to use. What’s more, the library provides some additional features, including the ability to display line numbers. Thus, if you’re wondering how to enable this functionality, the following example should show you how:

<!doctype html>

<html>

<head>

<meta charset=utf-8>

<title>Using Google Code Prettify Syntax highlighter (turning on line numbering)</title>

<!-- Include the JavaScript dependencies -->

<script src="google-code-prettify/prettify.js"></script>

<!-- Include the default styles -->

<link href="google-code-prettify/prettify.css" type="text/css" rel="stylesheet" />

<style type="text/css">

body {

    padding: 0;

    margin: 0;

    background: #fff;

    font: 1em Arial, Helvetica, sans-serif;

    color: #000;

}

#wrapper {

    width: 800px;

    margin: 0 auto;

}

</style>

</head>

<body>

    <div id="wrapper">

        <header>

            <h1>Using Google Code Prettify Syntax highlighter (turning on line numbering)</h1>

                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>

        </header>

        <section id="code-section">

            <header>

                <h2>Sample code section</h2>

            </header>

            <pre class="prettyprint linenums">

            <code>

    &lt;?php   

    namespace SampleApp\Common; 

     class ServiceLocator implements RegistrableInterface

    {

        protected $_resources = array(); 

         /**

         * Set the specified resource

         */

        public function set($key, AbstractResource $resource)

        {

            if (!isset($this-&gt;_resources[$key])) {

                $this-&gt;_resources[$key] = $resource;

            }

            return $this;          

        } 

         /**

         * Get the specified resource

         */

        public function get($key)

        {

            if (isset($this-&gt;_resources[$key])) {

                return $this-&gt;_resources[$key];

            }

            throw new \InvalidArgumentException('The requested resource does not exist.');

        } 

         /**

         * Remove the specified resource

         */

        public function remove($key)

        {

            if (isset($this-&gt;_resources[$key])) {

                unset($this-&gt;_resources[$key]);

                return $this;

            }

            throw new \InvalidArgumentException('The resource to be removed does not exist.');

        }

         

        /**

         * Check if the specified resource exists

         */

        public function exists($key)

        {

            return isset($this-&gt;_resources[$key]);

        }     

    }

            </code>

            </pre>

        </section>

        <footer>

            <header>

                <h2>Footer section</h2>

            </header>

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>

        </footer>

    </div>

    <script>

    prettyPrint();

    </script>   

</body>

</html>

As this whole new example demonstrates, turning on the line numbering feature is as simple as assigning a class called “linenums” to the <pre> element that wraps up the target code sample. Logically, the example in question would be rather incomplete if I didn't show you the result that it produces. Fear not, as the following image does exactly that:

Not too bad, right? As one might expect, Google Code Prettify is a solid contender that will make your life much easier when it comes to highlighting code snippets in (X)HTML documents. It’s easy to setup and use, and additionally it includes some appealing abilities that turn it into a good candidate for occupying a privileged place in the toolbox of many web designers around.   

Final Thoughts

In this second installment of this series, I took a close look at two more popular contenders in the terrain of syntax highlighting: in this particular case, the libraries that were put under analysis were Highlight.js  and Google Code Prettify, which - as you just saw - are a breeze to configure and use. Although it’s valid to point out that these two don’t provide the bunch of additional features included with SyntaxHighlighter, they do work great when it comes to spicing up the look of online code snippets.

So far, all the libraries that have been showcased are standalone JavaScript packages, which is all well and fine. But, does this mean that currently there’s not any jQuery plug-in that accomplishes a similar task? Well, in fact there’re a decent variety of them. However, one of the best performers (in my personal opinion, of course) is beautyOfCode, a powerful wrapper for Alex Gorbatchev‘s SyntaxHighlighter that adds some nice features, and which you’ll fall in love with almost immediately.

This one will be the library that will be covering in depth in the last installment, so don’t miss it!


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

All JavaScript Tutorials
More By Alejandro Gervasio


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials