Wednesday, June 21, 2017

Highlighted (syntax) code snippets in Blogger

My blogs being technical in nature often contain snippets of code. The old technique I was using for correctly highlighting them no longer works because the library I was using has gone the way of the dinosaurs. Thankfully, however, there is a much better (and slightly easier) way to achieve this using the highlight.js library (https://highlightjs.org/).


Procedure:
  1. In your main Blogger page, from the pane on the left (which contains 'Posts', 'Stats', etc.) click on 'Theme'.
  2. In the frame that reloads on the right first choose 'Backup / Restore' and then 'Download theme' to save a backup of the unmodified theme before we mess with it.
  3. Press 'Close' to close the dialog/pop-up window and choose 'Edit HTML'.
  4. Before the </head> tag paste the following lines:
    
    <link href='//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.8.0/styles/agate.min.css' rel='stylesheet'/>
    <script src='//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.8.0/highlight.min.js'/>
    <script>hljs.initHighlightingOnLoad();</script>
    
  5. Choose 'Save Theme'

Note:   I chose to use the 'agate' theme (CSS), there are many others. You can take a look at the available options at https://highlightjs.org/static/demo/. To choose another one simply replace "agate" in the link with the theme you like.

Similarly, 'highlight.min.js' only supports a core of 35 common languages. To highlight other languages add additional scripts you can find at https://cdnjs.com/libraries/highlight.js/



Example:

Now to place a code snippet in your blog simply switch to "HTML" editing (instead of "Compose") and place the snippet inside a <pre><code> </code></pre> block or simply inside <code> </code> if quoting code inline. You can specify the language inside the "class" element of the "code" block (visit the highlight.js website for more details).

To create the following highlighted python snippet:
    def factorial(n):
        if n == 0:
            return 1
        else:
            return n * factorial(n - 1)

I used the following code in HTML mode:
    <pre><code class="python">    def factorial(n):
        if n == 0:
            return 1
        else:
            return n * factorial(n - 1)
    </code></pre>

Simple and elegant. Enjoy.

Note: To place HTML itself inside a highlighted snippet (very meta indeed, I needed it for the last section of code) you will have to escape all of the HTML. I used https://www.freeformatter.com/html-escape.html.

No comments:

Post a Comment