Sunday, May 27, 2012

Posting source code on blogger

As this is a blog about a coding project, it certainly makes sense to have a nice way of posting source code. I just ran into this when trying to format the shell line
sage -b lattices
in the previous post. This might not seem like a very sophisticated thing, but there will probably be longer pieces of (Python) code, eventually, and so I wanted to do it right from the start.

Apparently, there is no built-in syntax highlighting on blogger. But there is SyntaxHighlighter, a very nice client-side syntax highlighting library. Integration on blogger is a little tricky though.

First, I had to switch the theme to a non-dynamic ("simple") theme in order to be able to edit its HTML code. But I prefer the design of this one anyway, and the annoying loading phase with those rotating gears seems to be gone now. Then, in the HTML template (which is actually XML markup with the HTML for the blog page inside it), I included the following after the <title>...</title> tag:
<link href="" rel="stylesheet" type="text/css"></link>
<link href="" rel="stylesheet" type="text/css"></link>
<script src="" type="text/javascript">
<script src='' type='text/javascript'/>
<script src='' type='text/javascript'/>
And the following goes right before the closing </body> tag:

To actually include highlighted source in the blog, you have to edit the raw HTML of your post and mark it as <pre>, like the following:
<pre class="brush: python">
if x: print y
This will render as:
if x: print y
To disable line numbers, add class="brush: python; gutter: false" (see the full list of options).

I'm still not sure how to markup inline code in the text: should I use the font menu and choose Courier (which is more convenient) or go to raw HTML and enter it as <code> (which is semantically correct)? Note that it doesn't even look the same.

Furthermore, I still don't like the way linebreaks and paragraphs are dealt with on blogger, and actually the whole way markup is generated. But after all, I still think it's good to have a hosted, ready-to-be-used blog for such a project and not having to set up (and most of all, maintain) everything yourself.


  1. There is a missing "/" to end the script tag on line 3 of the stuff that you need to add between the title tags.
    Thanks for the writeup!

  2. so how about inserting a java code in blogger posts? any suggestions?

  3. This has been one of my long-time frustrations in Blogger. I think I've tried this solution (in an earlier iteration, perhaps?) and was unimpressed, as well as a couple others. I almost migrated everything over to WordPress as a result.

    I'll give this another whirl. Thanks for posting.

  4. I was looking for finally met also.
    Thank you, Greetings from