Thursday, December 11, 2008

Publishing source code in Blogger

Wow it worked! Sucks I still have to escape all my > and < s but way better than what I was doing before (manual formatting).

So this took me a while to figure out... maybe I can do a step-by-step to help someone else out there out... there are a lot of pages on how to do this, I needed to combine them to make it work.

K... so... inside your blogger Dashboard go Layout - Edit HTML.

Paste this just before the </head> tag:


<link href='http://syntaxhighlighter.googlecode.com/svn/trunk/Styles/SyntaxHighlighter.css' rel='stylesheet' type='text/css'/>


Then paste this just before the </body> tag


<script language='javascript' src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js'/>

<script language='javascript' src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js'/>

<script language='javascript' src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js'/>

<script language='javascript' src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js'/>

<script class='javascript'>
//<![CDATA[
function FindTagsByName(container, name, Tag)
{
var elements = document.getElementsByTagName(Tag);
for (var i = 0; i < elements.length; i++)
{
if (elements[i].getAttribute("name") == name)
{
container.push(elements[i]);
}
}
}

var elements = [];
FindTagsByName(elements, "code", "pre");
FindTagsByName(elements, "code", "textarea");

for(var i=0; i < elements.length; i++) {
if(elements[i].nodeName.toUpperCase() == "TEXTAREA") {
var childNode = elements[i].childNodes[0];
var newNode = document.createTextNode(childNode.nodeValue.replace(/<br\s*\/?>/gi,'\n'));
elements[i].replaceChild(newNode, childNode);
}
else if(elements[i].nodeName.toUpperCase() == "PRE") {
brs = elements[i].getElementsByTagName("br");
for(var j = 0, brLength = brs.length; j < brLength; j++) {
var newNode = document.createTextNode("\n");
elements[i].replaceChild(newNode, brs[0]);
}
}
}

//clipboard does not work well, no line breaks
//dp.SyntaxHighlighter.ClipboardSwf = "http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/clipboard.swf";
dp.SyntaxHighlighter.HighlightAll("code");
//]]>
</script>


Save your template.

Then to test it out create a new post and put some sample code between two PRE tags, like this:

<pre name="code" class="html">
<!-- code here -->
</pre>

BUT you have to use escape characters for html
Here's a link to a site to help you do that quickly:
http://www.accessify.com/tools-and-wizards/developer-tools/quick-escape/default.php


And here are the links to the posts that helped me figure this out:
http://www.accessify.com/tools-and-wizards/developer-tools/quick-escape/
http://azowebsphere.blogspot.com/2008/08/how-to-post-code-snippets-in-blogger.html

No comments: