AddThis

Monday, March 28, 2016

Syntax Highlighting

Blog Enhancements

I've been rocking Alex Gorbatchev's syntax highlighter for a while on this blog, and it I really liked it.  It was quick and easy to use and at the time but lately, and for the past few years, I've really been into darker themes.  The syntax highlighter didn't appeal to me anymore and I didn't particularly like the themes they had.  So I searched around and stumbled upon Prism.  I like the way Prism looks and I found the installation super simple.  Take a look below at a code sample:


  var bubbleSort = function(unsorted) {
    for (var i = 0; i < unsorted.length; i++) {
      var swapped = false;
      for (var j = i + 1; j < unsorted.length; j++) {
        if (unsorted[i] > unsorted[j]) {
          var tmp = unsorted[j];
          unsorted[j] = unsorted[i];
          unsorted[i] = tmp;

          swapped = true;
        }
      }
      if (!swapped) {
        return unsorted;
      }
    }
    return unsorted;
  };
If you too want syntax highlighting like this, this is how!


Instructions

  1. Include the theme stylesheet
    
          <head>
            <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.4.1/themes/prism-okaidia.min.css" rel="stylesheet" type="text/css"></link>
          </head>
        
  2. Include the prism javascript file and all the languages you want highlighted, say you wanted support for ruby
    
          <body>
            ...
            <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.4.1/prism.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.4.1/prism-ruby.min.js"></script>
          </body>
        
  3. Wrap your code that you want highlighted
     
      <pre><code class="language-ruby">
        puts 'hi' 
      </code></pre>
      
  4. Done! You should get something like the following:
     
        puts 'hi'
      



Extra

For more information, definitely check out their site http://prismjs.com/.
And once you find the theme you like and language you want highlighted, stop over here for a nice cdn that will serve up the javascript and css's that you need https://cdnjs.com/libraries/prism.

No comments: