Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I was looking for an easy to implement code highlighter for my Blog and after searching around and trying out various different ones I settled on highlight.js. My requirements were simple, it had to work with the BBcode used in Flatpress and ideally to not require much code change.

What I really liked about highlight.js is it automatically figures out the code language i.e. it's syntax and highlights accordingly, of course there is a way to force a particular language too. There is also a way to tell it not to highlight something, a feature that I use as the default option on my Blog (for backwards compatibility of old blog posts).

This is a quick jsFiddle I set up to try it out...
highlightjs.png


It worked pretty well!

To integrate this into Flatpress, I changed the BBcode plugin to have two additional parameters on the [code] block - highlight and syntax i.e. it would look like this...
 BBcode
[code highlight syntax=js]
[/code]


If the highlight parameter is present, the 'nohighlight' class would not be used i.e. highlighting would be enabled.

The value for the syntax parameter is one of the languages from this list. I made this parameter optional so if it's left out then highlight.js will automatically detect the syntax to use.

The last change I had to do to the BBcode plugin was to add a wp_footer hook that would call the hljs.highlightBlock() method exactly as it is in the jsFiddle linked above. That ensures that the method is called just once after the page is loaded.

So if you're looking for a code highlighter that is easy to set up and integrate into your Blog, highlight.js is the way to go.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.