Tuesday, March 29, 2011

Blogspot Source Code Formatting

I've added several posts which contain formatted source code on this blog, and each and every time I had to go into the HTML editor to manually convert code characters into HTML entities. For example if I want to use a greater than bracket which is common in coding, I have to modify the html code and write > etc...

Another blogger has posted a very neat script which grabs your source code and converts it into proper HTML so that the format isn't affected. It even keeps the proper tab spacing.

http://formatmysourcecode.blogspot.com/2006/02/paste-your-text-here.html

Here is an example snippet of code that comes from this script:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    cout << "Hello World!" << endl;
    return 0;
}

Now thats very handy!

BUT!  Then I decide to write a modifier which would add line numbers using a two column table.  I decided on using a table instead of two divs in order to prevent copying line numbers if we want to highlight and copy the code.  Here is an example of the output of the modifier. It is basically the code I wrote to modify the original javascript into generating line numbers. There are a couple of extra helper JS lines to call this function and provide the required parameters, but the core of the functionality is in this function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function ReturnCodeWithNumbers(strCode, intLineNum)
{
    // Generate the line numbers
    strLineCode = "";
    strLines = "";
    for (k=1;k<intLineNum+1;++k)
    {
    strLines += k + "\n";
    }

    if ( document.getElementById("embedstyle").checked )
    {
    strLineCode = "<pre style=\"font-family: Andale Mono, Lucida Console, ";
    strLineCode += "Monaco, fixed, monospace; color: #000000; background-color: #eee;";
    strLineCode += "font-size: 12px;border: 1px dashed #999999;line-height: 14px;";
    strLineCode += ";padding: 5px; overflow: auto; width: 100%\"><code>";
    strLineCode += strLines + "</code></pre>";
    }
    else
    {
    strLineCode = "<pre class=\"source-code\"><code>" + strLines + "</code></pre>";
    }

    // Generate the table with all the contents
    strTranslate = "<table style=\"cellspacing:0; boder:0;\"><td>" + strLineCode;
    strTranslate += "</td><td>" + strCode + "</td></table>";
    return strTranslate;
}

1 comment:

  1. Nice post...
    For eclipse IDE users, found a eclipse plugin to directly copy the code as HTML.

    http://java-sample-program.blogspot.com/2012/12/copy-as-html-eclipse-plugin.html

    ReplyDelete