Friday, 24 September 2010

How to Post Code in Blog{er,spot}

This was a collossal pain in the arse to work out, but actually turned out to be quite easy to implement. Y'see when you post text to a blog post everything works fine. The problem is if you try to post code - html, linux command line stuff. You end up with lots of special characters that the site tries to render in HTML instead of just displaying. So instead of (for example) a line which shows the code to get coloured text, you just get the coloured text. Not helpful.

There are many and varied explanations of how to do this, but I prefer this way which is cobbled together from multiple sources. For my epic Amiga Linux project I needed to be able to display commands to type in AND the outputs of commands. I wanted to have those blocks distinct from each other and the surrounding text. This is what I eventually came up with.

Go to the Design tab, and choose the Edit HTML section. You get a text box which behaves much in the same way as the post editting box. Scroll down until you get to a line which says:

]]></b:skin>

Insert above that line the following text:

.postCode{
background:#eeeeee; 
border:1px solid #A6B0BF; 
font-size:120%; 
line-height:100%; 
overflow:auto; 
padding:10px; 
color:#000000
}
.postOutput{
background:#000000; 
border:1px solid #A6B0BF; 
font-size:120%; 
line-height:100%; 
overflow:auto; 
padding:10px; 
color:#eeeeee
}

My workflow is then to copy the text I am working on into some website or other which will automatically convert all the special characters to their escape codes.

Then I paste the resulting text into the blog editing window in HTML mode. I then switch to compose mode, and change all of the code or output text into quotes. I then switch back to the HTML mode, copy all of the HTML text and paste it into a text editor.

I then do a search and replace all "/blockquote" entries for "/pre" and then "blockquote" for "pre class="postCode"". That converts all of the quotes to the code class that I defined above. It is black text (the colour is 00 for all RGB) on a nearly white background (ee in all RGB - ff for all would be completely white).

I then sift through the post and check for any postCode classes that I need to change to postOutput. That is nearly white text on a black background, which gives good contrast between the two texts. If I do actually want to quote something I do it last.

I end up with the following tag regime for the two types of quoted code:

<pre class="postCode"> code </pre>
or
<pre class="postOutput"> output </pre>

No comments:

Post a Comment