What I Wanted
On occasion, I write code and publish it here, so I wanted a way to format it nicely. Fortunately for me, I didn't have to look far before I found exactly what I want, I found it over at Roger Johansson's 456 Berea St. With what I wanted in mind, it was just a matter of doing it.
The jQuery
Here is the JavaScript code:
$(document).ready(function() {\n
// Looks for a block of code inside a div with the class 'conver'\n
$("div.convert code").each(function() {\n
$this = $(this);\n
$codetext = $this.html(); // Grabs the code in each code block\n
if ($.browser.msie) { // For IE, ugh... Split at the explicit \\n's and remove the last element\n
$codetext = $codetext.split(/\\\\n\\n|\\\\n|\\n/);\n
$codetext.pop();\n
} else { // For modern browsers, remove explicit \\n's, split at implicit \\n's and remove first and last elements\n
$codetext = $codetext.replace(/\\\\n/g, '');\n
$codetext = $codetext.split(/\\n/);\n
$codetext.shift();\n
$codetext.pop();\n
// Mark the code so the css knows we are working with a modern browser\n
$("div#content").addClass("w3c");\n
}\n
$ordlist = $('<ol></ol>');\n
// Remove the old code and do some renaming\n
$this.parent().empty().append($ordlist).removeClass("convert").addClass("code");\n
// For each line, take the code and put in a 'li' in the 'ol' and append everything\n
for (var index in $codetext) {\n
numTabs = 0;\n
if ($codetext[index].match(/\\t/g) != undefined) {\n
numTabs = $codetext[index].match(/\\t/g).length;\n
}\n
$listitem = $("<li></li>");\n
$listitemcode = $('<code></code>');\n
if (!$.browser.msie) {\n
classtabs = 'tabs' + numTabs;\n
$listitemcode.addClass(classtabs);\n
}\n
$listitemcodetext = ($codetext[index]) ? $codetext[index] : ' ';\n
$ordlist.append($listitem);\n
$listitem.append($listitemcode);\n
$listitemcode.html($listitemcodetext);\n
}\n
})\n
});\n
Following is the snippet of code you put the code you want to format in.
Sample HTML
<div class="convert">
<code>
</code>
</div>
Early samples of the code fell apart when I tried using html, even using < and > it broke, but I make it past that. Next, I discovered that IE doesn't really handle line breaks like a normal browser, so I had to make a caveat, you have to manually add '\n' at the end of each line, I am still working on that though and will post future fixes in subsequent posts.