How to write an article using highlight.js

July 2, 2015 by Melvin

After setting up the website let's start with a first blog entry. To experience the awesomeness of the great it-world we often use code. With highlight.js there is already a great script to highlight code snippets on a website. We will go through a short "how-to"-tutorial.


Include Library

Either you download the Javasript and CSS files from the official download page and include them in your website's head:

<link rel="stylesheet" href="~/path/to/styles/default.css">
<script src="~/path/to/highlight.pack.js"></script>

... or you use them from a CDN. For example we take them from cdnjs:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>

Write your Code

Write your code in the <body> inside of the <pre><code>...</code></pre> tags. Normally highlight.js will automatically detect the language you use. If not you can choose the language by your own with the class attribute.

<pre><code class="html">...</code<pre/>

There is a list of the classes for the different languages available. For no highlightning just use the "nohighlight" class. To make it work add the following to your <head>.

<script>hljs.initHighlightingOnLoad();</script>

Customize your Design

We started with the standard look which comes within the default.css stylesheet. But you can change the design of your code just with including other CSS-files from or customize it by yourself. Highlight.js uses classes for syntactic elements. In the CSS classes reference you can find the class names. Use them with the hljs- prefix as a CSS selector. For accessing the whole code snippet use the class selector .hljs.

JavaScript Example: VisualStudio Dark Style

As an example for a customized design we created a stylesheet for a layout like Microsoft's Visual Studio. Our CSS-file looks like this:

code.vs.hljs {
    background-color: #0E1E1E;
    color: white;
}
code.vs.javascript .hljs-keyword,
code.vs.javascript .hljs-literal{ /*special literal: “true”, “false” and “null”*/
    color: #569CD6;
}
code.vs.javascript .hljs-comment{
    color: #608B4E;
}
code.vs.javascript .hljs-number{
    color: #B5CEA8;    
}
code.vs.javascript .hljs-built_in, /*built-in objects and functions (“window”, “console”, “require”, etc...)*/
code.vs.javascript .hljs-title, /*name of a function inside a header*/
code.vs.javascript .hljs-params, /*parentheses and everything inside them in a function’s header*/
code.vs.javascript .hljs-pi, /*‘use strict’ processing instruction*/
code.vs.javascript .hljs-function{  
    color: white;
}
code.vs.javascript .hljs-string{
    color: #D69D85;    
}
code.vs.javascript .hljs-regexp{
    color: #9A5334;
}

Usually the .hljs- selectors apply on every language. Therefore we added the additional class-selector javascript.

Write your JavaScript code between the <pre><code>...</code></pre> tags.

<pre><code class="javascript">function $initHighlight(block, flags) {
  try {
    if (block.className.search(/\bno\-highlight\b/) != -1)
      return processBlock(block.function, true, 0x0F) + " class=''";
  } catch (e) {
    /* handle exception */
    var e4x = "alert!";
  }
  for (var i = 0 / 2; i < classes.length; i++) { // "0 / 2" should not be parsed as regexp
    if (checkCondition(classes[i]) === undefined)
      return /\d+[\s/]/g;
  }
  console.log(Array.every(classes, Boolean));
}
</code></pre>

The result should look like this:

function $initHighlight(block, flags) {
  try {
    if (block.className.search(/\bno\-highlight\b/) != -1)
      return processBlock(block.function, true, 0x0F) + " class=''";
  } catch (e) {
    /* handle exception */
    var e4x = "alert!";
  }
  for (var i = 0 / 2; i < classes.length; i++) { // "0 / 2" should not be parsed as regexp
    if (checkCondition(classes[i]) === undefined)
      return /\d+[\s/]/g;
  }
  console.log(Array.every(classes, Boolean));
}

CSS Example

To style the CSS design like in Visual Studio add the following code to your stylesheet.

code.vs.css .hljs-tag,
code.vs.css .hljs-id,
code.vs.css .hljs-class,
code.vs.css .hljs-attr_selector,
code.vs.css .hljs-pseudo
{
    color: #D7BA7D;
}
code.vs.css .hljs-at_rule{
    color: #569CD6;
}
code.vs.css .hljs-comment{
    color: #57A64A;
}
code.vs.css .hljs-attribute{
    color: #9CDCFE;    
}
code.vs.css .hljs-value,
code.vs.css .hljs-number,
code.vs.css .hljs-hexcolor,
code.vs.css .hljs-important,
code.vs.css .hljs-function{
    color: #C8C8C8;    
}
code.vs.css .hljs-string{
    color: #D69D85;    
}

Choose your code and write it in your <body>

<pre><code class="css">@media screen and (-webkit-min-device-pixel-ratio: 0) {
  body:first-of-type pre::after {
    content: 'highlight: ' attr(class);
  }
  body {
    background: linear-gradient(45deg, blue, red);
  }
}
@import url('print.css');
@page:right {
 margin: 1cm 2cm 1.3cm 4cm;
}
@font-face {
  font-family: Chunkfive; src: url('Chunkfive.otf');
}
div.text,
#content,
li[lang=ru] {
  font: Tahoma, Chunkfive, sans-serif;
  background: url('hatch.png') /* wtf? */;  color: #F0F0F0 !important;
  width: 100%;
}
</code></pre>

Your result of the code snippet should look like this:

@media screen and (-webkit-min-device-pixel-ratio: 0) {
  body:first-of-type pre::after {
    content: 'highlight: ' attr(class);
  }
  body {
    background: linear-gradient(45deg, blue, red);
  }
}
@import url('print.css');
@page:right {
 margin: 1cm 2cm 1.3cm 4cm;
}
@font-face {
  font-family: Chunkfive; src: url('Chunkfive.otf');
}
div.text,
#content,
li[lang=ru] {
  font: Tahoma, Chunkfive, sans-serif;
  background: url('hatch.png') /* wtf? */;  color: #F0F0F0 !important;
  width: 100%;
}

HTML Example

To present HTML code we add the HTML selectors into our CSS-file.

code.vs.html .hljs-tag{
    color: #B4B4B4;
}
code.vs.html .hljs-doctype,
code.vs.html .hljs-title{
    color: #569CD6;
}
code.vs.html .hljs-comment{
    color: #57A64A;
}
code.vs.html .hljs-attribute{
    color: #9CDCFE;    
}
code.vs.html .hljs-value{
    color: #C8C8C8;    
}
code.vs.html .hljs-pi{
    color: #808080;    
}         
code.vs.html .hljs-cdata{
    color: #DCDCDC;
}

Now the tags of your HTML code have to be recognized as part of the snippet. Therefore the angle brackets should be replaced with &lt; or &gt; as you see in the example code snippet:

<pre><code class="html">&lt;?xml version="1.0"?&gt;
&lt;response value="ok" xml:lang="en"&gt;
  &lt;text&gt;Ok&lt;/text&gt;
  &lt;comment html_allowed="true"/&gt;
  &lt;ns1:description&gt;&lt;![CDATA[
  CDATA is &lt;not&gt; magical.
  ]]&gt;&lt;/ns1:description&gt;
  &lt;a&gt;&lt;/a&gt; &lt;a/&gt;
&lt;/response&gt;
&lt;!DOCTYPE html&gt;
&lt;title&gt;Title&lt;/title&gt;
&lt;style&gt;body {width: 500px;}&lt;/style&gt;
&lt;script type="application/javascript"&gt;
  function $init() {return true;}
&lt;/script&gt;
&lt;body&gt;
  &lt;p checked class="title" id="title"&gt;Title&lt;/p&gt;
  &lt;!-- here goes the rest of the page --&gt;
&lt;/body&gt;
</code></pre>

Your result should look like this:

<?xml version="1.0"?>
<response value="ok" xml:lang="en">
  <text>Ok</text>
  <comment html_allowed="true"/>
  <ns1:description><![CDATA[
  CDATA is <not> magical.
  ]]></ns1:description>
  <a></a> <a/>
</response>
<!DOCTYPE html>
<title>Title</title>
<style>body {width: 500px;}</style>
<script type="application/javascript">
  function $init() {return true;}
</script>
<body>
  <p checked class="title" id="title">Title</p>
  <!-- here goes the rest of the page -->
</body>

Include jsfiddle

There is another nice way to show your HTML, CSS and JavaScript code using jsfiddle. It comes with its own highlightning style. Just include it with an iframe tag into your website.

<iframe width="100%" height="300" src="http://jsfiddle.net/melmatical/3/wf3v6utv/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>

It is a big advantage to see all the code in the same frame together with its result. On the other hand you are limited to only those three languages where highlight.js comes with over 100 different languages.

C# Example

As we are right in the mood we add the styling for C#.

code.vs.csharp .hljs-keyword{
    color: #569CD6;
}
code.vs.csharp .hljs-comment,
code.vs.csharp .hljs-xmlDocTag{
    color: #57A64A;
}
code.vs.csharp .hljs-number{
    color: #B5CEA8;    
}
code.vs.csharp .hljs-string{
    color: #D69D85;    
}
code.vs.csharp .hljs-title,
code.vs.csharp .hljs-class{
    color: #4EC9B0;
}
code.vs.csharp .hljs-preprocessor,
code.vs.csharp .hljs-function{
    color: #DCDCDC;    
}

Choose your sample C#-code and write it in the <body>. But do not forget to change the anglebrackets.

<pre><code class="csharp">using System;
#pragma warning disable 414, 3021
public class Program
{
    /// <summary>The entry point to the program.</summary>
    public static int Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
        string s = @"This
""string""
spans
multiple
lines!";
        return 0;
    }
}
async Task<int> AccessTheWebAsync()
{
    // ...
    string urlContents = await getStringTask;
    return urlContents.Length;
}
</code></pre>

Your result of the code snippet should look like this:

using System;
#pragma warning disable 414, 3021
public class Program
{
    /// <summary>The entry point to the program.</summary>
    public static int Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
        string s = @"This
""string""
spans
multiple
lines!";
        return 0;
    }
}
async Task<int> AccessTheWebAsync()
{
    // ...
    string urlContents = await getStringTask;
    return urlContents.Length;
}

Line Numbers

Unfortunately highlight.js does not come with line numeration. Without the additional numbers the code is easier to read but sometimes they are helpful. We add the following JavaScript code to our website. Over the id we access the element where we want to add the line numeration.

function spanLineNumber(num) {
    return "<span class='lineNumber'>" + num + "</span> "
}
$(document).ready(function () {
    var myCode = $("pre code#codeId").text();
    var start = 1;
    myCode = spanLineNumber(start) + myCode;
    var numCode = myCode.replace(/\n/g, function () {
        start++;
        return "\n" + spanLineNumber(start);
    });
    $("pre code#codeId").html(numCode);
});

Color the line numbers.

code.javascript.vs .lineNumber .hljs-number{
    color: #2B91AF;    
}

And you get the result.

var Vector = (function () {
    function Vector(x, y, z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
    Vector.times = function (k, v) {
        return new Vector(k * v.x, k * v.y, k * v.z);
    };
    Vector.minus = function (v1, v2) {
        return new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
    };
    Vector.plus = function (v1, v2) {
        return new Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
    };
    return Vector;
})();