Tuesday, April 16, 2013

Displaying Highlighted XML Code in Blogger Like A Real Astronaut

Excerpt from the little-known Apollo 21 mission transcripts:

"Houston, this is Tranquility Base. We can put XML and other source code in our blog posts and it looks pretty cool. Over."

"Roger, Tranquility Base. We're pickin' up that code and it looks real nice."

I'm far from being any kind of XML or Web whiz kid, but this only took about 700 hours to figure out. If you Google things like "display code in blogger", you'll come up with a lot of hits. Most of them don't really hit the mark, so here's what I did, in an Austin Powers Nutshell.

  1. Look at Mike Samuel's Prettify.
  2. Edit your Blogger template HTML.
  3. Load Prettify just before the end of the body.

There! You can now insert code with syntax highlighting, optional numbers, etc.

<?xml version="1.0" encoding="UTF-8"?>
<device class="system" subclass="thin client">
  <manufacturer>Cisco</manufacturer>
  <product>VXC 6215</product> 
  <subproduct/>
  <partnumber/>
  <cpu>AMD G-T56N</cpu>
  <memory>
    <capacity>4000</capacity>
    <installed>2000</installed>
  </memory>
  <storage type="flash">
    <capacity>4000</capacity>
  </storage>
</device>

If the code to be displayed is XML (as in the example above) you have a bit more work to do.

First off, the <pre> and <code> tags are not enough to protect your XML from being processed by the browser. They'll disappear and leave you with just the element values, which is useless. You need to convert all the angle brackets to their HTML equivalents. It's obnoxious, but I couldn't find a way around it.

So keep a link handy to a tool like Postify. This will "escape" all of the characters that will confuse a browser. Paste your code in (using the HTML tab -- not the Compose tab), copy the translated code out and into a <pre class="prettyprint"> block.

I had to do one more thing: fix the colors. The default colors don't work at all in my chosen blog template. I checked out the skin gallery and picked one called "Desert". It's pretty close to the Blogger template and to the Tango Dark theme I use in Emacs.

Just append that skin to the prettify loader you put into the template. Beware that the skin example on Mike's Google page contains an ampersand. Blogger will choke on that and demand a semicolon after the skin parameter. Just escape the ampersand with && and you're good to go.

I don't care for the HTML-style line numbering. I'd rather see numbers in the left margin, like Emacs' "line-num.el" or Vim's ":set number".

No comments:

Post a Comment