Since this blog is usually about tech and stuff, some of the posts contain code. When I see code it bothers me that it’s not syntax highlighted, for improved readability. So as it turns out I recently stumbled upon microlight.js, which provides “reasonable”-ish syntax highlighting. The beauty of microlight.js is that it is language-independent, and light (2.2 kb minimized!). Of course, it doesn’t beat real syntax highlighting but that wasn’t its purpose.
Now one slight problem is how to add microlight.js to my blog, which runs under the Ghost platform. The way microlight.js works is that you insert the class
microlight in whichever HTML tag (usually a
div I guess?) where you want to have syntax highlighting. However, Ghost uses Markdown, and automatically spits out HTML for you. I could dive into the Ghost source code, find the part where it spits out the HTML for code snippets, and encounter some headaches next time I have to update Ghost (which is already a pain to update).
Or, as it turns out, I could modify the source code of microlight.js itself. And it was stupidly simple, barely even a line of code to change. I cloned the microlight.js repo, and in the microlight.js file modified the line that selects the elements to modify. That’s the
microlighted = _document.getElementsByClassName('microlight'); part, that I simply changed to
microlighted = _document.getElementsByTagName('code');. Easy.
Then just load the script (via Ghost’s new Code Injection feature) and done!