Styling Code Samples with YUL
Inspired by Dunstin's Tag Transformations for pretty code samples, Dustin's Get Elements by Class Name, and using the Yahoo! User Interface Library (again), I've hacked together a little script to transform the contents of a pre tag into a somewhat nicely formatted listing.
There's some problems with it. I'm using innerHTML. There's a nicer DOM standards friendly way to do this, but for now this will work. I'll update this later, maybe. For now, the code samples here and there (in places where I bothred to use class="code") look a little nicer (but the code still sucks... :-P).
It's not exactly like Dunstan's. He's using an ordered list. I've got the ol tag inside the pre tag still. If I go to something DOM-ish, I should have the ol get built as a DOM object, remove the pre, then insert the ol.
The colors don't bleed past the end of the width of the visible pre area. When there is overflow, and you have to scroll, the line colors don't continue.
Here's the code...
Update: The old code was here... I made it a little more DOM friendly below.
sPt = {
rtrim: function (str) {
str = this != window ? this : str;
while ( (str.charAt(str.length - 1) == ' ') || (str.charAt(str.length - 1) == '\n') )
str = str.substring(0, str.length - 1);
return str;
},
stylePreTags: function () {
var pts = getElementsByClass('code', document, 'pre')
for (var i=0; i < pts.length; i++) {
var pt = pts[i];
var c = pt.innerHTML.rtrim();
var lns = c.split("\n");
var ol = document.createElement("ol");
ol.className = pt.className;
var alt = 0;
for (var j=0; j < lns.length; j++) {
li = document.createElement("li");
li.innerHTML = lns[j];
var tbs = 0;
var cls = "";
while (lns[j].charAt(tbs) == "\t")
tbs++;
cls = (tbs > 0) ? ("tab" + tbs + " ") : "";
cls += (alt==0) ? "line" : "alt_line";
li.className = cls;
ol.appendChild(li);
alt = 1 - alt;
}
pt.parentNode.replaceChild(ol, pt);
}
}
}
String.prototype.rtrim = sPt.rtrim;
YAHOO.util.Event.addListener(window, 'load', sPt.stylePreTags);
Trackback: http://philsown.org/2006/03/styling-code-samples-with-yul/trackback
How to Put Your Face Next to Your Comment