Thursday 7 January 2010

How to display source code with line numbers and formatting in blogger

While setting up this blog, I realised I wanted some nicely formatted source code. As I'm blogging about coding, even if it is for my own use mainly, I wanted a solution that made the source code easy to read.

I settled on (after not too long a search) these two ideas which I have combined into one....


OK, so the css solution works like a charm, no need to go into detail here just pop over to the link above for details. Kudos to The Blogger Guide.

However, I had to tweak the line numbers solution. Again, most of the description at that site is valid, but I changed the way the new content is generated, not least using lists rather than tables. This should still  allow for content to be copied and pasted ok too.

Enjoy :)


Anyway, I'm not going through everything here as it's all been covered in the two links above. but I have posted the javascript and css I'm using on this site as a starting point:

CSS
pre {     border:1px dashed #aaaaaa;     background:#eeeeee;     white-space:pre;     font-family:monospace;     font-size:9pt;     line-height: 10pt;     height:auto;     width:auto;     padding:5px;     overflow:auto; } ol.pre {     margin: 0 0 0 15px;      padding: 0px;      padding-left: 5px; } .pre li {     margin: 0;     padding: 0;      background: none !important; }
and the JavaScript
function showLineNumbers() {
    /****************************************
    * Written by Andreas Papadopoulos       *
    * http://akomaenablog.blogspot.com      *
    * akoma1blog@yahoo.com                  *
    *                                       *
    * And heavily refactored by Matt Keeble *
    * http://codinginharmony.blogspot.com   *
    ****************************************/
    
    var isIE = navigator.appName.indexOf('Microsoft') != -1;
    var preElems = document.getElementsByTagName('pre');
    if (preElems.length == 0) return;

    for (var i = 0; i < preElems.length; i++) {
        var pre = preElems[i];
        var oldContent = pre.innerHTML;
        oldContent = oldContent.replace(/ /g," ");
        oldContent = oldContent.replace(/\n/g, "<br />");
        var strs = oldContent.split("<br />");
        
        if (isIE) {
            strs = oldContent.split("<BR />");
        }
                
        if(oldContent.substring(0,4) == '<br />')
        {
            oldContent = oldContent.substring(4);
        }
        
        newContent = '<ol class="pre">';
        if(strs.length == 1)
        {
            newContent+= "<li>"+strs+"</li>";
        } 
        else
        {        
            for(var j=0; j < strs.length; j++) {
                if(strs[j] !== '')    newContent += "<li>"+strs[j]+"</li>"
            }
        }
        newContent+= "</ol>";
        pre.innerHTML = newContent;
    }
}

No comments:

Post a Comment

Please leave your feedback and comments. I love to discuss this stuff!