Using Pygments to colour our training examples
Archive - Originally posted on "The Horse's Mouth" - 2013-03-10 17:48:28 - Graham EllisA browser receives text in a stream - as black and white, if you like. But the human eye prefers colour, so that's how modern, syntax aware editors display it for you, highlighting particular aspects of the text such as html tags in a different colour. Look what I mean:

For a number of years, we've published all the examples on our training courses, and extra blogged examples and examples written during courses too, indexed module by module - navigate here. Initially, they were monochrome, but over time I've added in syntax parsers to add some rudimentary colour. For PHP it was easy, using the highlight_string function, for other languages a little more tricky and I'll admit to not event trying with HTML ... until today!
My previous few blogs have been about HTML - a modern revision of the basics for staff and delegates who need to brush up before they look after our sites, or start generating code via Django, Rails, PHP or something else. And the examples weren't as easy to read as I would have wished.
If you want to do a job and you find yourself thinking "Surely someone has done this before" then: a) They probably have b) They have probably released it open source! |
And so I found a lovely little Python package called Pygments and a command line utility to run it called pygmentize. You can find it too at http://pygments.org/. Easy to install - short and straightforward instructions and some local testing - the examples in the image above show such a test.
There's a huge number of languages and formats supported - Python, PHP, Ruby, Tcl, Perl, C, C++ and even Lua to support all of our current langauges. There's Java too. And lots of other interesting markups too including - for my initial purposes - HTML.
I've installed Pygments on our live server, and I have it highlighting all our HTML example files. I can now, proudly, publicise examples like our HTML one-of-each form sample, and our Cascading style sheet training examples. I'm leaving it at that for a few days - making sure it settles well, making sure I've not upset any other apple cart; we didn't use TDD (Test Driven Development) for the site, so we're somewhat lacking in wider ranging validators.