Wednesday, June 17, 2020

Syntax Highlighting Code in Blogger

I was using Syntax Highlighter created by Alex Gorbatchev to highlight code snippets on this blog, but of late, it was not working or taking too long to load up. 
So it was time again to figure out a new way to do this and there were a few options that work in a similar fashion:
The other option was to pre-format code and then paste it into your post:

I found Code Prettier to be the simplest option that can get me closest to Syntax Highlighter and the setup is very easy - just need to add these lines to the theme HTML code:

<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>
<style>
li.L0, li.L1, li.L2, li.L3,
li.L5, li.L6, li.L7, li.L8 {
  list-style-type: decimal !important;
}
</style>

Once this is done, all you need to do is to put encoded code snippet in a pre block with the class set to prettyprint and viola!
Note that the above code has a style override which makes line numbers show up on all lines of code. Without that block of style code, only every fifth line of could would have a line number.

Here is an example of the pre block that you need to use to syntax highlight your code:
 <pre class="prettyprint linenums lang-sh"> ... your code ... </pre>

You don't need to specify the language since prettyPrint will guess it, however you can specify a language by specifying the language extension along with the prettyprint class. Languages supported out of the box are:
"bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html", "java",
"js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh", "xhtml", "xml","xsl"
You may also use the HTML 5 convention of embedding a <code> element inside the <pre> and using language-java style classes:
  <pre class="prettyprint"><code class="language-java">...</code></pre>
Note: Remember to escape your code using HTML entities :)

LinkWithin

Related Posts Plugin for WordPress, Blogger...