Code boxes with syntax highlighting in online documentation

Technical documentation, especially software documentation, often shows code samples. With the help of an appropriate JavaScript library, code snippets can be presented in a particularly user-friendly way:

  • Commands and parameters are displayed in color, depending on the programming language or markup used (syntax highlighting).
  • There is a function to directly copy or save the displayed code.
  • There is a horizontal scroll function for long lines of code if needed.

Example

This website also uses code boxes with automatic syntax highlighting and a copy function for its code examples. Take a look at the code snippets in the “Implementation” section below.

Implementation

The solution presented here uses the open-source JavaScript library Prism.

For the design, you can choose from various themes. For advanced functions, there are various plugins available to be used in combination with the library. When downloading the library, you must select which theme and plugins you want to use and in which programming languages the content is to be displayed. The more options you select, the larger the download will be and thus the longer it will take your online documentation to load the library. Therefore, limit yourself to what you actually need.

Step 1: In the head section of your page template, link to the CSS file of the library (adjust the path as necessary).


<link rel="stylesheet" href="YOUR-PATH/prism.css">

Step 2: At the end of the body section of your page template, include the library JavaScript (again, adjust the path as necessary).


<script src="YOUR-PATH/prism.js"></script>

Step 3: You can use any number of code blocks in your text. Such a code block looks like this (replace the stated language with the language of the code to be displayed):


<pre><code class="language-USED-LANGUAGE">
 YOUR-CODE-SAMPLE
</code></pre>

Example: Imagine you want to display the code of the following JavaScript function in your document.


function myFunction(p1, p2) {
  return p1 * p2;
}

This results in:


<pre><code class="language-javascript">
function myFunction(p1, p2) {
  return p1 * p2;
}
</code></pre>

Important: To prevent the browser from trying to directly interpret the content to be shown as HTML, you need to replace left angle brackets with the HTML entity &lt; and right angle brackets with the HTML entity &gt;. Thus, an example with HTML code looks like this:


<pre><code class="language-html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
 &lt;body&gt;
  &lt;p&gt;Hello world!&lt;/p&gt;
 &lt;/body&gt;
&lt;/html&gt; 
</code></pre>

The result will be displayed like this:


<!DOCTYPE html>
<html>
 <body>
  <p>Hello world!</p>
 </body>
</html>