Home arrow JavaScript arrow Popular JavaScript Syntax Highlighters
JAVASCRIPT

Popular JavaScript Syntax Highlighters


This JavaScript tutorial will showcase some of the most popular syntax highlighters on the web, and demonstrate how to implement them on your site or blog.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 4
July 25, 2011

print this article
SEARCH DEVARTICLES

This JavaScript tutorial will showcase some of the most popular syntax highlighters on the web, and demonstrate how to implement them on your site or blog.

Being one of the most valuable allies of technical-minded bloggers and ezines around the web (like our own Developer Shed network), JavaScript syntax highlighters are powerful tools, whose ability is focused on turning a bunch of dull and arid code snippets into aesthetically pleasing and more readable pieces that keep visitors coming back for more.

While there’s nothing inherently wrong with this approach, it’s fair to say that it can become cumbersome and inefficient, especially when it comes to displaying code fragments that scope an extensive number of languages and technologies. So, if you’re facing this typical scenario, syntax highlighting libraries can be real time-savers, as they will let you perform the entire “cosmetic” process in an unobtrusive and quick way and - best of all - without having to sacrifice the carefully-crafted semantic meaning of your markup.

As one might expect, there’s a huge and plethoric variety of JavaScript syntax highlighters that can be used right out of the box with pretty satisfactory results. In this case, and for the sake of brevity, I’ll be taking a close look at only five of them, which according to my personal opinion, are the top of the list, due to the bulk of rich features that they offer and their flat learning curve.

SyntaxHighlighter

The first contender of this roundup is SyntaxHighlighter (http://alexgorbatchev.com/SyntaxHighlighter/), a full-featured and popular JavaScript syntax highlighter developed by Alex Gorbatchev in 2004. The package offers support for over 22 different languages (for the complete language list, check here (http://alexgorbatchev.com/SyntaxHighlighter/manual/brushes/), which are parsed and highlighted via a set of independent files called “brushes”.

Installing and using the library is a snap; all that you’ll need to do is include some JavaScript and CSS dependencies into the corresponding web page, and put the highlighter to work with a single line of code. In addition, if you don’t want to deal with the hassles of downloading files from here and there, there’s a free, self-hosted version of SyntaxHighlighter, which you can have a look at here: (http://alexgorbatchev.com/SyntaxHighlighter/hosting.html). So, if you’re planning to use this option, be a generous soul and contribute to pay the hosting service.

Having outlined what the library offers to the average designer, it’s time to show how to put it in action. Thus, below I created a simple example, which uses the package for highlighting a sample PHP fragment. Have a look at it:     

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Using Alex Gorbatchev's SyntaxHighlighter (default theme)</title>
<!-- Include the JavaScript dependencies -->
<script src="syntaxhighlighter_3.0.83/scripts/shCore.js"></script>
<script src="syntaxhighlighter_3.0.83/scripts/shBrushPhp.js"></script>
<!-- Include the core styles and default theme -->
<link href="syntaxhighlighter_3.0.83/styles/shCore.css" rel="stylesheet" type="text/css" />
<link href="syntaxhighlighter_3.0.83/styles/shThemeDefault.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
#wrapper {
    width: 800px;
    margin: 0 auto;
}
</style>
</head>
<body>
    <div id="wrapper">
        <header>
            <h1>Using Alex Gorbatchev's SyntaxHighlighter (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 class="brush: php">
            &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]);
                }     
            }
            </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
    SyntaxHighlighter.all();
    </script>
</body>
</html>

As seen above, getting SyntaxHighlighter up and running is only a matter of including a few dependencies and calling the program with the line “SyntaxHighlighter.all()”. Also, you should note that the PHP snippet being highlighted has been wrapped inside a <pre> element, which has been assigned a class called “brush: php”. Obviously, this is required for the program to work specifically with PHP code, but it’s possible to use different “brushes”, according to the language that needs to be parsed.

Also, in the previous example the library uses a default CSS theme (which naturally can be easily switched over others). So, if you’re wondering how the sample code looks after being massaged with SyntaxHighlighter, take a look at the following snapshot:

As the above image depicts, the library does a superb job highlighting code samples, as it not only beautifies the code itself, but it also adds line numbers, a gutter and a small toolbar as well. It’s worth pointing out that all these extra goodies can be enabled and disabled at will via a set of configuration options; for the moment, though, I’ll leave this task as homework for you, in case you want to customize the library’s default behavior.

And speaking of default things, you already saw that SyntaxHighlighter’s default CSS theme is more than enough for making your code samples look stylish and readable. However, it’s dead simple to change the default theme with a different one. To do so, all that you need to do is to include the corresponding CSS file and you’ll be set.

What’s more, the example below shows how to use the library with its “RDark” theme:

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Using Alex Gorbatchev's SyntaxHighlighter (RDark theme)</title>
<!-- Include the JavaScript dependencies -->
<script src="syntaxhighlighter_3.0.83/scripts/shCore.js"></script>
<script src="syntaxhighlighter_3.0.83/scripts/shBrushPhp.js"></script>
<!-- Include the core styles and RDark theme -->
<link href="syntaxhighlighter_3.0.83/styles/shCore.css" rel="stylesheet" type="text/css" />
<link href="syntaxhighlighter_3.0.83/styles/shThemeRDark.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
#wrapper {
    width: 800px;
    margin: 0 auto;
}
</style>
</head>
<body>
    <div id="wrapper">
        <header>
            <h1>Using Alex Gorbatchev's SyntaxHighlighter (RDark 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 class="brush: php">
            &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]);
                }     
            }
            </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
    SyntaxHighlighter.all();
    </script>  
</body>
</html>

While this example looks nearly identical to the first one, there’s a subtle difference that you’ve probably spotted: as I said before, this time the library uses its “RDark” CSS theme to highlight the same PHP code sample. This small change produces the following output:

That looks pretty engaging too! This shows in a nutshell how easy it is to tweak the behavior of SyntaxHighlighter, and why it has become one of the most popular syntax highlighting libraries available nowadays.

To sump up: SyntaxHighlighter is a powerful package that will fit the requirements of even the pickiest web designer, due to the bunch of appealing features that it brings to the table. Add to this its snappy installation and nearly zero configuration, and you’ll end up with a hard-to-beat contender in the field.

SHJS

As the name suggests, SHJS stands for Syntax Highlighting in JavaScript and its source files can be downloaded from here (http://shjs.sourceforge.net/doc/download.html). The library is capable of highlighting over 40 different languages and putting it to work is a straightforward process that can be tackled with minor hassles.

To get the library up and running, you’ll need to include in your web page the main script (main.min.js), then the file corresponding to the language that will be highlighted, and finally the CSS theme of your choice (to see the full list of available themes, be sure to check this URL [http://shjs.sourceforge.net/css/]). It’s that simple, actually.

As usual, the best manner to see how SHJS works is by example. In line with this concept, below I recreated the one that you learned previously, which this time uses the library to beautify the same PHP fragment using its default CSS theme. Check it out:

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Using SHJS Syntax highlighter (default theme)</title>
<!-- Include the JavaScript dependencies -->
<script src="shjs/sh_main.min.js"></script>
<script src="shjs/sh_php.min.js"></script>
<!-- Include the default CSS theme -->
<link href="shjs/sh_style.css" rel="stylesheet" type="text/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 SHJS 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 class="sh_php">
    &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]);
        }     
    }
            </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
    sh_highlightDocument();
    </script> 
</body>
</html>

Understanding how SHJS works is quite easy. Once the required dependencies have been downloaded (notice the use of the “sh_php.min.js” file, which takes care of highlighting PHP fragments), the code sample is parsed by calling the “sh_highlightDocument()” function. Similar to its previous competitor, the library requires you to wrap your code samples inside a <pre> element and add to it the required CSS class (in this case one called “sh_php”).   

Finally, this process generates the following outcome when visualized in most modern browsers:

There you have it. While it’s fair to admit that the output produced by SHJS doesn’t have all the bells and whistles of its rival SyntaxHighlighter, it yields more than satisfactory results. Moreover, if you’re wondering if it can be easily tweaked to function with a different theme, other than the default one, have a look at the example below, which highlights the already familiar PHP snippet, but in this case using the library’s Acid theme: 

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Using SHJS Syntax highlighter (Acid theme)</title>
<!-- Include the JavaScript dependencies -->
<script src="shjs/sh_main.min.js"></script>
<script src="shjs/sh_php.min.js"></script>
<!-- Include the CSS theme -->
<link href="shjs/sh_acid.min.css" rel="stylesheet" type="text/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 SHJS Syntax highlighter (Acid 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 class="sh_php">
    &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]);
        }     
    }
            </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
    sh_highlightDocument();
    </script>  
</body>
</html>

Here, it’s clear to see that the only change that was made in order to use the aforementioned Acid CSS theme was to include on the web page a file called “sh_acid.min.css” and nothing else. This subtle modification makes the sample PHP portion look like this:
 

Not bad at all, right? As you can see, switching over different themes with SHJS is a breeze to achieve. Not to mention that the library does an excellent job highlighting pieces of several languages, as it functions in a clean and unobtrusive manner that doesn’t collide with the web page’s markup.

In summary: if you don’t need to have at you disposal all the goodies that SyntaxHighlighter provides right out the box, but do want a syntax highlighter that supports a huge number of languages, SHJS is certainly an option worth looking.  

Final Thoughts

In this introductory chapter of this tutorial, I made a quick review of the two first participants of this list of JavaScript syntax highlighters. In this case, the contenders that were put under judgment were SHJS and Alex Gorbatchev‘s SyntaxHighlighter, being this last one (in my humble opinion), the most appealing package of this partial roundup, because of its top-notch features and snappy implementation.

However, this journey hasn’t been finished yet, as there’re still three additional libraries that need to be analyzed in depth, including Google Code Prettify, Highlight.js and beautyOfCode. But, fear not as these ones will be covered in the coming installments.

So, stick with my usual recommendation and don’t miss the next part!


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