Highlight.js for Ghost (Live Preview)

If you are a geek like myself and grabbed a copy of the first release of ghost, probably the first thing you did was try to add syntax highlighting.

I personally favored the Highlight.js solution; its simple, to the point and enabled me to use my favorite syntax theme, tomorrow-night.

However, the solution lacked the live preview side of Ghost; when blogging you can't really see your code being highlighted in the markdown editor which is kinda annoying to me, so I dug in and made it work all thanks of course to this post which helped me put the bits and pieces together.

The solution
  • First off, install highlight.js as explained in the post above, here it is if you get finger cramps scrolling up the page.
  • Next, open up core/server/views/default.hbs in your favorite text editor and right before </body> add the following lines:

    {{! Code highlighting with highlight.js }}
    <link rel="stylesheet" href="http://yandex.st/highlightjs/7.4/styles/THEME_NAME.min.css">
    <script src="http://yandex.st/highlightjs/7.3/highlight.min.js"></script>
    <script>
      var timeout, entry = $('.entry-markdown');
    
    
      function highlightCode(){
        $('pre code').each(function(i, e){hljs.highlightBlock(e)});
      }
    
    
      if(entry){
        $(document).keypress(function(event) {
          clearTimeout(timeout);
          timeout = setTimeout(highlightCode, 2001);
        });
      }
    
    
      setTimeout(function() {
        $('.content-list-content li').click(function() {
          highlightCode();
        });
      }, 500);
    </script>
    
  • Finally restart Ghost and give it a try !