Free javascript Hosting


CodeColorizer6.js

Uploaded on Nov 04 2009 03:31 by dopey

//Code colorizer for C like languages eg. C, C++, C#, JavaScript, Java etc
///////////// UTILS /////////////////
String.prototype.Trim = function () {
if (typeof(this) === "undefined")//Can "this" ever be undefined?
{
return "";
}
return this.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
};

function defined(obj)
{
return typeof(obj) !== "undefined";
}

///////////// START /////////////////

function Token(input, start, length, type)
{
this.Input = input;
this.Start = start;
this.Length = length;
this.Type = type;
this.Value = function () {
return this.Input.substr(this.Start, this.Length);
};
}

function JavaCodePatterns()
{
this.KeywordPattern = "\\b(?:abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\\b";
this.CommentPattern = "(?://.*?(?=\\r|\\n))|(?:/\\*.*?\\*/)";
this.StringPattern = "\"[^\"]*\"";

//Note: The order is important here. Any given entry has higher priority over the entries to its right (if any).
this.Patterns = [this.CommentPattern, this.StringPattern, this.KeywordPattern];
//NOTE: The order of the following elements must match the above order
this.PatternType = ["comment", "string", "keyword"];

this.CombinedPattern = "("+this.Patterns.join(")|(")+")";

this.CombinedRegEx = new RegExp(this.CombinedPattern, "g");
}


function CppCodePatterns()
{
this.KeywordPattern = "\\b(?:and|and_eq|asm|auto|bitand|bitor|bool|break|case|catch|char|class|compl|const|const_cast|continue|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|false|float|for|friend|goto|if|inline|int|long|mutable|namespace|new|not|not_eq|operator|or|or_eq|private|protected|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_cast|struct|switch|template|this|throw|true|try|typedef|typeid|typename|union|unsigned|using|virtual|void|volatile|wchar_t|while|xor|xor_eq)\\b";
this.CommentPattern = "(?://.*?(?=\\r|\\n))|(?:/\\*.*?\\*/)";
this.StringPattern = "\"[^\"]*\"";
this.PreprocessorPattern = "#\\s*(?:define|error|import|undef|elif|if|include|using|else|ifdef|line|endif|ifndef|pragma)\\b";

//Note: The order is important here. Any given entry has higher priority over the entries to its right (if any).
this.Patterns = [this.CommentPattern, this.StringPattern, this.KeywordPattern, this.PreprocessorPattern];
//NOTE: The order of the following elements must match the above order
this.PatternType = ["comment", "string", "keyword", "preprocessor"];

this.CombinedPattern = "("+this.Patterns.join(")|(")+")";

this.CombinedRegEx = new RegExp(this.CombinedPattern, "g");
}

function CSharpCodePatterns()
{
this.KeywordPattern = "\\b(?:abstract|event|new|struct|as|explicit|null|switch|base|extern|object|this|bool|false|operator|throw|break|finally|out|true|byte|fixed|override|try|case|float|params|typeof|catch|for|private|uint|char|foreach|protected|ulong|checked|goto|public|unchecked|class|if|readonly|unsafe|const|implicit|ref|ushort|continue|in|return|using|decimal|int|sbyte|virtual|default|interface|sealed|volatile|delegate|internal|short|void|do|is|sizeof|while|double|lock|stackalloc|else|long|static|enum|namespace|string)\\b";
this.CommentPattern = "(?://.*?(?=\\r|\\n))|(?:/\\*.*?\\*/)";
this.StringPattern = "\"[^\"]*\"";
this.PreprocessorPattern = "#\\s*(?:if|else|elif|endif|define|undef|warning|error|line|region|endregion)\\b";

//Note: The order is important here. Any given entry has higher priority over the entries to its right (if any).
this.Patterns = [this.CommentPattern, this.StringPattern, this.KeywordPattern, this.PreprocessorPattern];
//NOTE: The order of the following elements must match the above order
this.PatternType = ["comment", "string", "keyword", "preprocessor"];

this.CombinedPattern = "("+this.Patterns.join(")|(")+")";

this.CombinedRegEx = new RegExp(this.CombinedPattern, "g");
}

function JsCodePatterns()
{
this.KeywordPattern = "\\b(?:break|else|new|var|case|finally|return|void|catch|for|switch|while|continue|function|this|with|default|if|throw|delete|in|try|do|instanceof|typeof)\\b";
this.CommentPattern = "(?://.*?(?=\\r|\\n))|(?:/\\*.*?\\*/)";
this.StringPattern = "\"[^\"]*\"|\'[^']*\'";

//Note: The order is important here. Any given entry has higher priority over the entries to its right (if any).
this.Patterns = [this.CommentPattern, this.StringPattern, this.KeywordPattern];
//NOTE: The order of the following elements must match the above order
this.PatternType = ["comment", "string", "keyword"];

this.CombinedPattern = "("+this.Patterns.join(")|(")+")";

this.CombinedRegEx = new RegExp(this.CombinedPattern, "g");
}

function VBScriptCodePatterns()
{
this.KeywordPattern = "\\b(?:Call|Case|Class|Const|Dim|Do|Loop|Else|Erase|Execute|ExecuteGlobal|Exit|Explicit|For|ForEach|Function|Get|If|Let|Next|OnError|Option|Private|Property|Public|Randomize|ReDim|Rem|Select|Set|Stop|Sub|Then|Wend|While|With)\\b";
this.CommentPattern = "(?:rem|\\').*?(?=\\r|\\n)";
this.StringPattern = "\"[^\"]*\"";

//Note: The order is important here. Any given entry has higher priority over the entries to its right (if any).
this.Patterns = [this.CommentPattern, this.StringPattern, this.KeywordPattern];
//NOTE: The order of the following elements must match the above order
this.PatternType = ["comment", "string", "keyword"];

this.CombinedPattern = "("+this.Patterns.join(")|(")+")";

this.CombinedRegEx = new RegExp(this.CombinedPattern, "gi");
}

function DefaultColorSelector()
{
this.ProcessToken = function(token) {
var style = token.Type;
var str = "<span class=\""+style+"\">" + token.Value() + "</span>";
return str;
};
}

function Colorizer(codeTags)
{
this.defaultColorSelector = new DefaultColorSelector();

//NOTE: We are using the default color selector for all languages for the time being
this.ColorSelectors = {};

this.CodePattern =
{
"jscode" : function() { return new JsCodePatterns(); },
"csharpcode" : function() { return new CSharpCodePatterns(); },
"cppcode" : function() { return new CppCodePatterns(); },
"javacode" : function() { return new JavaCodePatterns(); },
"vbscriptcode" : function() { return new VBScriptCodePatterns(); }
};

this.Run = function()
{
for(var i=0; i<codeTags.length; ++i)
{
var language = codeTags[i].getAttribute("class");
if(language === null)
{
//Work around for IE
language = codeTags[i].getAttribute("className");
}
if(typeof(this.CodePattern[language]) === "undefined")
{
if(typeof(console) !== "undefined")
console.debug("Skipping <pre> tag with unknown language \"%s\".", language);
continue;
}

var cSrc = this.Colorize(codeTags[i].innerHTML, language);
//codeTags[i].innerHTML = cSrc;
// Workaround for IE <PRE> innerHTML normalization quirk
if (codeTags[i].tagName == "PRE" && "outerHTML" in codeTags[i])
{
//Works in IE and chrome
codeTags[i].outerHTML = "<pre class=\"" + language + "\">" + cSrc + "</pre>";
}
else
{
//Firefox doesn't seem to have outerHTML
codeTags[i].innerHTML = cSrc;
}
}
};

this.Colorize = function(src, language)
{
var tokenStream = this.Parse(src, language);

if(tokenStream.length === 0)
{
return "";
}

var colorSelector = this.ColorSelectors[language];
if( typeof(colorSelector) === "undefined")
{
colorSelector = this.defaultColorSelector;
}

var retVal = "";
var lastIndex = 0;

for(var i=0; i<tokenStream.length; i++)
{
retVal += src.substring(lastIndex, tokenStream[i].Start);
retVal += colorSelector.ProcessToken(tokenStream[i]);
lastIndex = tokenStream[i].Start + tokenStream[i].Length;
}
//Note: using substr and not substring
retVal += src.substr(lastIndex);

return retVal;
};

this.Parse = function(src, language)
{
var codePatterns = this.CodePattern[language]();
//var regEx = new RegExp(codePatterns.CombinedPattern, "g");
var regEx = codePatterns.CombinedRegEx;

var arrx;
var tokenStream = [];
while ((arrx = regEx.exec(src)) !== null)
{
for(var i=1; i<arrx.length; i++)
{
if(defined(arrx[i]) && arrx[i].Trim() !== "")
{
var len = regEx.lastIndex-arrx.index;
var type = codePatterns.PatternType[i-1];
tokenStream.push(new Token(src, arrx.index, len, type));
}
}
}
return tokenStream;
};
}


if(typeof(console) != "undefined")
console.debug("CodeColorizer6.js loaded");

Back to list