Friday, March 20, 2009

Line numbering source code snippet using Javascript for-loop hard coding

Here is a quick-and-dirty method of adding line numbers to the source code snippet.

program Hello_World ;

begin

   writeln('Hello, World !');

   { This method of line numbering is not so smart.
     The line numbers on the left is generated
     using a Javascript for-loop with hard-coding the
     number of loops which is 12. }

end.

The method is very simple : use a HTML table tag with only 1 row of 2 cells. The right cell is the code snippet. In the left cell, use Javascript to call a for-loop to document.writeln the line number.

The text inside both cells is inside a HTML pre tag. As long as they are of the same fonts and line heights, the line number will match the source code snippet.

Following coding snippet is contained inside a table of one cell :

program Hello_World ; begin writeln('Hello, World !'); { This method of line numbering is not so smart. The line numbers on the left is generated using a Javascript for-loop with hard-coding the number of loops which is 12. } end.

Using the same method, the line numbers are added :

program Hello_World ; begin writeln('Hello, World !'); { This method of line numbering is not so smart. The line numbers on the left is generated using a Javascript for-loop with hard-coding the number of loops which is 12. } end.

Now, the table consists of 2 cells in a row. The left cell is for line numbers.

The disadvantages of this method are:

  1. One disadvantage of this method is that the number of loop is hard-coded. You have count the total number of lines in your source code snippet and put this number in the for-loop.
  2. Another disadvantage is with the browser and blogspot.
    If the convert-line-breaks option is turn on in blogspot and you are using Firefox to read this page, the above table should be very perfect. The Pascal program end statement is at the line-12. But, if you are using IE6, the program end statement is at line-8. This is because the IE6 does not shown the blank lines from Blogger. There should be each of one blank line in between the statements program, begin, writeln, the block comment and the end statements. So, in order to take care of readers using IE6 and the convert-line-breaks is yes in blogspot, you have to count the number of blank lines and do a re-calculation on the final maximum number of lines for using in the for-loop.
    However, it the convert-line-breaks is NO, there is no such problem.
    Now, I have turn off the convert-line-breaks in my blog in blogsport and this page does not have this problem.


No comments:

Duplicate Open Current Folder in a New Window

Sometimes after I opened a folder in Win7, I would like to duplicate open the same folder again in another explorer window. Then, I can ope...