Tuesday 9 October 2007

Syntax highlighter script

I have been trying to write a simple script in JavaScript to highlight source code in a element such as the code.

Here is the code:

/*
Syntax highlighter for source code
Copyright (c) 2007 Samuel Saint-Pettersen
This script is licensed under the GPL
http://www.gnu.org/copyleft/gpl.html
*/

function syntaxHighlight()
{
var element = "code"; // element for source code
var attrib = "class"; // attibute for language

// count all code elements
var codes = document.getElementsByTagName(element);

// get contents and class value for each code element
for(var a = 0; a < codes.length; a++)
{
var code = codes[a];
var contents = code.innerHTML;
var language = code.className;

if(language == "boo")
{
// define first keywords
var keyw1 = new Array();
keyw1[0] = "def";
keyw1[1] = "print";
keyw1[2] = "if";

// colour first keywords
for(var b = 0; b < keyw1.length; b++)
{
var regex = new RegExp(keyw1[i], "ig");
var matched = contents.match(regex);
var keyword = matched.toString();
var repl = keyword.fontcolor("blue");
codes[i].innerHTML = contents.replace(regex, repl);
}
}
}
}

Problem I have with this code is that after the first keyword is coloured, the loop does not seem to continue. Hmmm... If anyone knows what I'm doing wrong, please leave a comment. Thanks.

Digg This Story

No comments: