Syntax highlight code snippets in Episerver - Part 1: The basics

Episerver is perhaps not the most used platform for developer blogs, but adding code snippets can be useful in other scenarios too.

Adding syntax highlighting to TinyMCE is easy, using the Code Sample plugin. It works well with both Prism.js and Highlight.js, two popular syntax highlighters. I will be using Hightlight.js as an example for the rest of this blog series.

Step 1: Add the Code Sample plugin

Add the plugin to your TinyMCE configuration, like this:

config.Default()
   .AddPlugin("codesample")
   .Toolbar("codesample");

This will add a new toolbar button.

Clicking the button will open a dialog that lets you choose a programming language, and insert a code snippet.

For information on how to customize the list of languages, see part 2. For information on how to configure TinyMCE for Episerver: see the documentation.

Add CSS and JavaScript, and call the init method.

<link rel="stylesheet" href="/path/to/styles/default.css">
<script src="/path/to/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

For more details, and custom initialization, refer to Hightlight.js usage.