This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.
  • Index
  •  » Advanced Topics
  •  » JavaScript-based syntax highlighter (using BBCode) for Scratch forums

#26 2011-12-21 12:18:50

blob8108
Scratcher
Registered: 2007-06-25
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

For the little isLetter function at the beginning, I'm sure that

Code:

var i;
for (i=0; i<=51; i++) {
    if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(i)==char) {
        return false;
    }
}

Could be replaced with something like

Code:

/[A-z]/.match(char)

-- I just can't remember precisely how JS regular expressions work. I'm sure you do, though, so that's okay.  smile


Things I've made: kurt | scratchblocks2 | this cake

Offline

 

#27 2011-12-21 13:59:42

scimonster
Community Moderator
Registered: 2010-06-13
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

blob8108 wrote:

For the little isLetter function at the beginning, I'm sure that

Code:

var i;
for (i=0; i<=51; i++) {
    if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(i)==char) {
        return false;
    }
}

Could be replaced with something like

Code:

/[A-z]/.match(char)

-- I just can't remember precisely how JS regular expressions work. I'm sure you do, though, so that's okay.  smile

I think what is wanted here is

Code:

if (!(/[A-Z]/i.test(char))) {return false;}

But then again, I'm not great at RegExp either...

Offline

 

#28 2011-12-21 21:05:04

nXIII
Community Moderator
Registered: 2009-04-21
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

Just use:

Code:

return 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(char) > -1

nXIII

Offline

 

#29 2011-12-22 01:34:26

Hardmath123
Scratcher
Registered: 2010-02-19
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

nXIII wrote:

Just use:

Code:

return 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(char) > -1

As usual, nXIII comes to save the day.  tongue

I'll CSS it up this afternoon, then patch up smilies and block glitches. Then work on HTML highlighting. Then I'm gone on my vacation...

EDIT: Smiley and block glitches fixed, nXIII's fix added, working on HTML editing and a better UI. Scimonster, would you mind permanently hosting this service on you dropbox?

Last edited by Hardmath123 (2011-12-22 03:38:53)


Hardmaths-MacBook-Pro:~ Hardmath$ sudo make $(whoami) a sandwich

Offline

 

#30 2011-12-22 04:06:12

Hardmath123
Scratcher
Registered: 2010-02-19
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

Testing HTML again, found some major issues:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="Highlighter.js"></script>
    </head>
    <body>
        <div id="preview"></div>
        <textarea id="toHighlight" rows=25 cols=150>/*Some code here*/</textarea><br/><input type="button" value="Highlight!" onclick="draw()" width="100"/>
        <br/><input type="radio" onclick="setLang(this.value)" value="JavaScript" name="lang" checked/> JavaScript
        <br/><input type="radio" onclick="setLang(this.value)" value="HTML" name="lang"/> HTML
        <br/><input type="radio" onclick="setLang(this.value)" value="Squeak" name="lang"/> Squeak
        <hr/>
        <br/><input type="radio" onclick="setMarkup(this.value)" value="HTML" name="mu" checked/> HTML
        <br/><input type="radio" onclick="setMarkup(this.value)" value="BBC" name="mu"/> BBC
    </body>
</html>


Hardmaths-MacBook-Pro:~ Hardmath$ sudo make $(whoami) a sandwich

Offline

 

#31 2011-12-22 08:43:15

Hardmath123
Scratcher
Registered: 2010-02-19
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

Wow... it can highlight the entire Scratch forums homepage perfectly in under 5 seconds. I'll post the new code here soon.


Hardmaths-MacBook-Pro:~ Hardmath$ sudo make $(whoami) a sandwich

Offline

 

#32 2011-12-22 13:22:34

Hardmath123
Scratcher
Registered: 2010-02-19
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

The completed Highlighter:

Code:

// Temporary variables: lang, markup, syntaxTokens, properties, blockTokens, commentTokens, char, inSet, tempVars, val
var lang="JavaScript";
var markup="HTML";
function isLetter(char)
{
    if(lang=="HTML")
    {
        return true;
    }
    return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".replace(char, "#") == "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
function draw()
{
    var syntaxTokens = [];
    var properties = [];
    var numericalTokens = [];
    var blockTokens = [];
    var commentTokens = [];
    var tempVars = [];
    var inSet = "";
    if (lang=="JavaScript")
    {
        syntaxTokens = ["if", "else", "var", "function", "return", "this", "new", "true", "false", "while", "break", "case", "switch", "for", "document", "window", "String", "Array", "Object", "Window", "Math"];
        numericalTokens = ["1","2","3","4","5","6","7","8","9","0"];
        blockTokens = [["\"", "\""], ["\'", "\'"]];
        commentTokens = [["/*", "*/"], ["//", "\n"]];
        tempVars = prompt("Temporary variables?", "something, nothing, anything").split(", ");
        properties=["getElementById", "getContext", "prototype", "constructor", "alert", "confirm", "prompt", "sqrt", "pow", "PI", "value", "innerHTML", "height", "width", "cols", "rows", "style", "onload", "onclick", "ondblclick", "onmouseover", "onmouseout", "onmousemove", "onmousedown", "onmouseup", "onkeyup", "onkeydown", "onkeypress", "onbeforeunload", "length", "charAt", "replace"];
    }
    if (lang=="HTML")
    {
        var tempTokens=["html", "head", "body", "!DOCTYPE", "p", "div", "span", "a", "script", "style", "input", "button", "textarea", "select", "option", "iframe", "frame", "br", "hr", "canvas", "abbr", "b", "i", "u", "s", "strong", "meta", "link", "title", "font", "tr", "td", "tbody", "table", "form", "label", "optgroup", "img", "noscript"];
        for (i=0; i<tempTokens.length; i++)
        {
            syntaxTokens.push("<"+tempTokens[i]+">");
            syntaxTokens.push("<"+tempTokens[i]+"/>");
            syntaxTokens.push("<"+tempTokens[i]);
            syntaxTokens.push("</"+tempTokens[i]+">");
        }
        syntaxTokens.push("/>");
        syntaxTokens.push(">");
        numericalTokens = ["1","2","3","4","5","6","7","8","9","0"];
        blockTokens = [["\"", "\""], ["\'", "\'"]];
        commentTokens = [["<!--", "-->"]];
        tempVars = ["::**::"];
        properties=["style", "height", "width", "rows", "cols", "onload", "onmouseover", "onmouseout", "onmousemove", "onmousedown", "onclick", "onmouseup", "onkeyup", "onkeydown", "onkeypress", "onchange", "onsubmit", "selected", "checked", "value", "type", "id", "name", "action", "src", "href", "class", "true", "false", "tabindex", "label", "for"];
        if (markup=="HTML")
        {
            for (i=0; i<syntaxTokens.length; i++)
            {
                syntaxTokens[i]=syntaxTokens[i].replace(/</g, "&lt;").replace(/>/g, "&gt;");
            }
            commentTokens = [["&lt;!--", "--&gt;"]];
        }
        alert(syntaxTokens.join("  ,  "));
    }
    if (lang=="Squeak")
    {
        syntaxTokens = ["ifTrue:", "ifFalse:", "ifNaN:", "whileTrue:", "whileFalse:", "timesRepeat", "self", "^", "_"];
        numericalTokens = ["1","2","3","4","5","6","7","8","9","0"];
        blockTokens = [["\'", "\'"]];
        commentTokens = [["\"", "\""]];
        tempVars = prompt("Temporary variables?", "something, nothing, anything").split(", ");
        properties = ["rounded", "reversed", "scrambled", "asUpperCase", "asLowerCase", "log", "exp", "raisedTo:", "sin", "cos", "tan", "degreesToRadians", "radiansToDegrees", "arcSin", "arcTan", "arcCos", "abs", "sqrt", "ln"];
    }
    //var toHighlight = prompt("Paste some code to highlight...", "...here.");
    var toHighlight=document.getElementById("toHighlight").value;
    String.prototype.wordBeginsAtIndex=function(word, index) {return (this.substr(index,word.length)==word)};
    String.prototype.insertAtIndex=function(word, index) {return this.substr(0, index)+word+this.substr(index)};
    var counter=0;
    if (markup=="HTML")
    {
        toHighlight=toHighlight.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;");
        while (counter<=toHighlight.length-1)
        {
            for (i=0; i<=commentTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(commentTokens[i][0], counter))
                {
                    //alert(1);
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#009900'>", counter);
                    //alert(toHighlight);
                    counter+=28+commentTokens[i][0].length;
                    while (!(toHighlight.wordBeginsAtIndex(commentTokens[i][1], counter) && (toHighlight.charAt(counter-1)!="\\" || (toHighlight.charAt(counter-1)+toHighlight.charAt(counter-2))=="\\\\")))
                    {
                        counter++;
                    }
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+commentTokens[i][1].length);
                    counter+=6+commentTokens[i][1].length;
                }
            }
            for (i=0; i<=syntaxTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(syntaxTokens[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+syntaxTokens[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#D100A5'>", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+28+syntaxTokens[i].length);
                    counter+=syntaxTokens[i].length+34;
                }
            }
            for (i=0; i<=tempVars.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(tempVars[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+tempVars[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#800080'>", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+28+tempVars[i].length);
                    counter+=tempVars[i].length+34;
                }
            }
            for (i=0; i<=properties.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(properties[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+properties[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#368288'>", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+28+properties[i].length);
                    counter+=properties[i].length+34;
                }
            }
            for (i=0; i<=numericalTokens.length-1; i++)
            {
                if (toHighlight.charAt(counter)==numericalTokens[i])
                {
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#0000FF'>", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+29);
                    counter+=35;
                }
            }
            for (i=0; i<=blockTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(blockTokens[i][0], counter))
                {
                    //alert(1);
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#FF0000'>", counter);
                    //alert(toHighlight);
                    counter+=28+blockTokens[i][0].length;
                    while (!(toHighlight.wordBeginsAtIndex(blockTokens[i][1], counter) && (toHighlight.charAt(counter-1)!="\\" || (toHighlight.charAt(counter-1)+toHighlight.charAt(counter-2))=="\\\\")))
                    {
                        counter++;
                    }
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+blockTokens[i][1].length);
                    counter+=6+blockTokens[i][1].length;
                }
            }
            counter++;
        }
        toHighlight=toHighlight.replace(/\n/g, "<br/>");
        toHighlight=toHighlight.replace(/\t/g, "&nbsp; &nbsp; &nbsp; ");
    }
    
    if (markup=="BBC")
    {
        toHighlight=toHighlight.replace(/\[/g, "[[i][/i]").replace(/\)\)/g, ")[i][/i])").replace(/\(\(/g, "([i][/i](").replace(/=/g, "=[i][/i]").replace(/:/g, ":[i][/i]");
        while (counter<=toHighlight.length-1)
        {
            for (i=0; i<=commentTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(commentTokens[i][0], counter))
                {
                    //alert(1);
                    toHighlight=toHighlight.insertAtIndex("[color=#009900]", counter);
                    //alert(toHighlight);
                    counter+=15+commentTokens[i][0].length;
                    while (!(toHighlight.wordBeginsAtIndex(commentTokens[i][1], counter) && (toHighlight.charAt(counter-1)!="\\" || (toHighlight.charAt(counter-1)+toHighlight.charAt(counter-2))=="\\\\")))
                    {
                        counter++;
                    }
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+commentTokens[i][1].length);
                    counter+=7+commentTokens[i][1].length;
                }
            }
            for (i=0; i<=syntaxTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(syntaxTokens[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+syntaxTokens[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("[color=#D100A5]", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+15+syntaxTokens[i].length);
                    counter+=syntaxTokens[i].length+22;
                }
            }
            for (i=0; i<=tempVars.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(tempVars[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+tempVars[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("[color=#800080]", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+15+tempVars[i].length);
                    counter+=tempVars[i].length+22;
                }
            }
            for (i=0; i<=properties.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(properties[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+properties[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("[color=#368288]", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+15+properties[i].length);
                    counter+=properties[i].length+22;
                }
            }
            for (i=0; i<=numericalTokens.length-1; i++)
            {
                if (toHighlight.charAt(counter)==numericalTokens[i])
                {
                    toHighlight=toHighlight.insertAtIndex("[color=#0000FF]", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+16);
                    counter+=16+7;
                }
            }
            for (i=0; i<=blockTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(blockTokens[i][0], counter))
                {
                    //alert(1);
                    toHighlight=toHighlight.insertAtIndex("[color=#FF0000]", counter);
                    //alert(toHighlight);
                    counter+=15+blockTokens[i][0].length;
                    while (!(toHighlight.wordBeginsAtIndex(blockTokens[i][1], counter) && (toHighlight.charAt(counter-1)!="\\" || (toHighlight.charAt(counter-1)+toHighlight.charAt(counter-2))=="\\\\")))
                    {
                        counter++;
                    }
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+blockTokens[i][1].length);
                    counter+=7+blockTokens[i][1].length;
                }
            }
            counter++;
        }
    }
    if (markup=="HTML")
    {
        document.getElementById("preview").innerHTML=(toHighlight);
        if (document.getElementById("genBox").value)
        {
            toHighlight="<div style='overflow:scroll; border-style:inset; border-width:2px; background-color:lavenderBlush; height:200px; width:400px;'><div style='margin-top:5px; margin-left:5px; font-family:trebuchet ms; font-size:12px;'><b>Code:</b><div style='font-family:monaco; font-size:10px;'><br/><br/>"+toHighlight+"</div></div></div>";
        }
    }
    document.getElementById("toHighlight").value=(toHighlight);
    document.getElementById("toHighlight").select();
}
function setLang(val)
{
    lang=val;
}
function setMarkup(val)
{
    markup=val;
}

Code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="Highlighter.js"></script>
    </head>
    <body>
        <div id="preview" style="font-family:monaco; font-size:12px; width:100%; height:300px; overflow:scroll;"><span style="color:grey">Your code will appear, formatted, over here if you pick the output markup as <q>HTML</q></span></div>
        <div style="height:300px;">
            <textarea id="toHighlight" style="float:left; font-family:monaco; font-size:12px; width:48%; height:100%;">/*Some code here*/</textarea>
            <div style="float:left; background-color:gainsboro; font-family:trebuchet ms; font-size:12px; width:49%; height:100%; border-style:inset; border-width:thin; border-color:blue;">
                <input type="radio" onclick="setLang(this.value)" value="JavaScript" name="lang" id="jsL" checked/> <label for="jsL">JavaScript</label>
                <br/><input type="radio" onclick="setLang(this.value)" value="HTML" name="lang" id="htmlL"/> <label for="htmlL">HTML</label>
                <br/><input type="radio" onclick="setLang(this.value)" value="Squeak" name="lang" id="sqL"/> <label for="sqL">Squeak</label>
                <hr/>
                <br/><input type="radio" onclick="setMarkup(this.value)" value="HTML" name="mu" id="htmlM" checked/> <label for="htmlM">HTML</label>&nbsp;&nbsp;[<input type="checkbox" id="genBox"/> <label for="genBox">Generate a formatted box, too.</label>]
                <br/><input type="radio" onclick="setMarkup(this.value)" value="BBC" name="mu" id="bbcM"/> <label for="bbcM">BBC</label>
                <hr/>
                <input type="button" value="Highlight!" onclick="draw()" style="width:100%; position: relative; bottom: 10px;"/>
            </div>
        </div>
    </body>
</html>

Bye, going to sleep.

Last edited by Hardmath123 (2011-12-22 13:24:35)


Hardmaths-MacBook-Pro:~ Hardmath$ sudo make $(whoami) a sandwich

Offline

 

#33 2011-12-22 13:44:28

BoltBait
Scratcher
Registered: 2009-03-09
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

Why write your own when others are available?

Check this one out:  http://shjs.sourceforge.net/

I've used it before.  It is good and fast.


Animated sigs must be banned!
http://boltbait.com/j.pnghttp://boltbait.com/s.pnghttp://boltbait.com/d.pnghttp://boltbait.com/a.pnghttp://boltbait.com/p.png

Offline

 

#34 2011-12-22 13:47:16

nXIII
Community Moderator
Registered: 2009-04-21
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

The isLetter(char) function

return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".replace(char, "#") == "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

only returns true if its argument is not a letter. If you wanted this, I'd suggest

return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(char) === -1;

Last edited by nXIII (2011-12-22 13:48:17)


nXIII

Offline

 

#35 2011-12-22 16:07:44

blob8108
Scratcher
Registered: 2007-06-25
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

BoltBait wrote:

Why write your own when others are available?

But writing your own code is so much more funtongue


Things I've made: kurt | scratchblocks2 | this cake

Offline

 

#36 2011-12-23 00:25:02

Hardmath123
Scratcher
Registered: 2010-02-19
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

nXIII wrote:

The isLetter(char) function

return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".replace(char, "#") == "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

only returns true if its argument is not a letter. If you wanted this, I'd suggest

return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(char) === -1;

I know, it's supposed to report true if char is not a letter. Basically, my code says "Look for a match with a keyword at a specified index. Then check if the letters before and after he keywords are alphabet. If so, you know the keyword is part of a larger word, thus it shouldn't be highlighted." That's why isLetter should report true (ie go ahead and highlight) if and only if the characters surrounding the keywords in question are not standard English alphabet.

EDIT: Line numbers in formatted code boxes:
http://www.imgpaste.com/PynT.png

Last edited by Hardmath123 (2011-12-23 02:00:26)


Hardmaths-MacBook-Pro:~ Hardmath$ sudo make $(whoami) a sandwich

Offline

 

#37 2011-12-23 02:18:43

Hardmath123
Scratcher
Registered: 2010-02-19
Posts: 1000+

Re: JavaScript-based syntax highlighter (using BBCode) for Scratch forums

Code:

// To-do list:
//(!) HTML not working
//(!) Libraries
//    Need better CSS

// Temporary variables: lang, markup, syntaxTokens, properties, blockTokens, commentTokens, char, inSet, tempVars, val
var lang="JavaScript";
var markup="HTML";
var isBeingHighlighted="";
function isLetter(char)
{
    if(lang=="HTML")
    {
        return true;
    }
    return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".replace(char, "#") == "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
function draw()
{
    var syntaxTokens = [];
    var properties = [];
    var numericalTokens = [];
    var blockTokens = [];
    var commentTokens = [];
    var tempVars = [];
    var inSet = "";
    if (lang=="JavaScript")
    {
        syntaxTokens = ["if", "else", "var", "function", "return", "this", "new", "true", "false", "while", "break", "case", "switch", "for", "document", "window", "String", "Array", "Object", "Window", "Math"];
        numericalTokens = ["1","2","3","4","5","6","7","8","9","0"];
        blockTokens = [["\"", "\""], ["\'", "\'"]];
        commentTokens = [["/*", "*/"], ["//", "\n"]];
        tempVars = prompt("Temporary variables?", "something, nothing, anything").split(", ");
        properties=["getElementById", "getContext", "prototype", "constructor", "alert", "confirm", "prompt", "sqrt", "pow", "PI", "value", "innerHTML", "height", "width", "cols", "rows", "style", "onload", "onclick", "ondblclick", "onmouseover", "onmouseout", "onmousemove", "onmousedown", "onmouseup", "onkeyup", "onkeydown", "onkeypress", "onbeforeunload", "length", "charAt", "replace"];
    }
    if (lang=="HTML")
    {
        var tempTokens=["html", "head", "body", "!DOCTYPE", "p", "div", "span", "a", "script", "style", "input", "button", "textarea", "select", "option", "iframe", "frame", "br", "hr", "canvas", "abbr", "b", "i", "u", "s", "strong", "meta", "link", "title", "font", "tr", "td", "tbody", "table", "form", "label", "optgroup", "img", "noscript"];
        for (i=0; i<tempTokens.length; i++)
        {
            syntaxTokens.push("<"+tempTokens[i]+">");
            syntaxTokens.push("<"+tempTokens[i]+"/>");
            syntaxTokens.push("<"+tempTokens[i]);
            syntaxTokens.push("</"+tempTokens[i]+">");
        }
        syntaxTokens.push("/>");
        syntaxTokens.push(">");
        numericalTokens = ["1","2","3","4","5","6","7","8","9","0"];
        blockTokens = [["\"", "\""], ["\'", "\'"]];
        commentTokens = [["<!--", "-->"]];
        tempVars = ["::**::"];
        properties=["style", "height", "width", "rows", "cols", "onload", "onmouseover", "onmouseout", "onmousemove", "onmousedown", "onclick", "onmouseup", "onkeyup", "onkeydown", "onkeypress", "onchange", "onsubmit", "selected", "checked", "value", "type", "id", "name", "action", "src", "href", "class", "true", "false", "tabindex", "label", "for"];
        if (markup=="HTML")
        {
            for (i=0; i<syntaxTokens.length; i++)
            {
                syntaxTokens[i]=syntaxTokens[i].replace(/</g, "&lt;").replace(/>/g, "&gt;");
            }
            commentTokens = [["&lt;!--", "--&gt;"]];
        }
        alert(syntaxTokens.join("  ,  "));
    }
    if (lang=="Squeak")
    {
        syntaxTokens = ["ifTrue:", "ifFalse:", "ifNaN:", "whileTrue:", "whileFalse:", "timesRepeat", "self", "^", "_"];
        numericalTokens = ["1","2","3","4","5","6","7","8","9","0"];
        blockTokens = [["\'", "\'"]];
        commentTokens = [["\"", "\""]];
        tempVars = prompt("Temporary variables?", "something, nothing, anything").split(", ");
        properties = ["rounded", "reversed", "scrambled", "asUpperCase", "asLowerCase", "log", "exp", "raisedTo:", "sin", "cos", "tan", "degreesToRadians", "radiansToDegrees", "arcSin", "arcTan", "arcCos", "abs", "sqrt", "ln"];
    }
    //var toHighlight = prompt("Paste some code to highlight...", "...here.");
    var toHighlight=document.getElementById("toHighlight").value;
    String.prototype.wordBeginsAtIndex=function(word, index) {return (this.substr(index,word.length)==word)};
    String.prototype.insertAtIndex=function(word, index) {return this.substr(0, index)+word+this.substr(index)};
    var counter=0;
    if (markup=="HTML")
    {
        toHighlight=toHighlight.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;");
        while (counter<=toHighlight.length-1)
        {
            for (i=0; i<=commentTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(commentTokens[i][0], counter))
                {
                    //alert(1);
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#009900'>", counter);
                    //alert(toHighlight);
                    counter+=28+commentTokens[i][0].length;
                    while (!(toHighlight.wordBeginsAtIndex(commentTokens[i][1], counter) && (toHighlight.charAt(counter-1)!="\\" || (toHighlight.charAt(counter-1)+toHighlight.charAt(counter-2))=="\\\\")))
                    {
                        counter++;
                    }
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+commentTokens[i][1].length);
                    counter+=6+commentTokens[i][1].length;
                }
            }
            for (i=0; i<=syntaxTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(syntaxTokens[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+syntaxTokens[i].length)))
                {
                    isBeingHighlighted="syntax";
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#D100A5'>", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+28+syntaxTokens[i].length);
                    counter+=syntaxTokens[i].length+34;
                    isBeingHighlighted="notsyntax";
                }
            }
            for (i=0; i<=tempVars.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(tempVars[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+tempVars[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#800080'>", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+28+tempVars[i].length);
                    counter+=tempVars[i].length+34;
                }
            }
            for (i=0; i<=properties.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(properties[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+properties[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#368288'>", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+28+properties[i].length);
                    counter+=properties[i].length+34;
                }
            }
            for (i=0; i<=numericalTokens.length-1; i++)
            {
                if (toHighlight.charAt(counter)==numericalTokens[i])
                {
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#0000FF'>", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+29);
                    counter+=35;
                }
            }
            for (i=0; i<=blockTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(blockTokens[i][0], counter))
                {
                    //alert(1);
                    toHighlight=toHighlight.insertAtIndex("<span style='color:#FF0000'>", counter);
                    //alert(toHighlight);
                    counter+=28+blockTokens[i][0].length;
                    while (!(toHighlight.wordBeginsAtIndex(blockTokens[i][1], counter) && (toHighlight.charAt(counter-1)!="\\" || (toHighlight.charAt(counter-1)+toHighlight.charAt(counter-2))=="\\\\")))
                    {
                        counter++;
                    }
                    toHighlight=toHighlight.insertAtIndex("</span>", counter+blockTokens[i][1].length);
                    counter+=6+blockTokens[i][1].length;
                }
            }
            counter++;
        }
        toHighlight=toHighlight.replace(/\n/g, "<br/>");
        toHighlight=toHighlight.replace(/\t/g, "&nbsp; &nbsp; &nbsp; ");
    }
    
    if (markup=="BBC")
    {
        toHighlight=toHighlight.replace(/\[/g, "[[i][/i]").replace(/\)\)/g, ")[i][/i])").replace(/\(\(/g, "([i][/i](").replace(/=/g, "=[i][/i]").replace(/:/g, ":[i][/i]");
        while (counter<=toHighlight.length-1)
        {
            for (i=0; i<=commentTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(commentTokens[i][0], counter))
                {
                    //alert(1);
                    toHighlight=toHighlight.insertAtIndex("[color=#009900]", counter);
                    //alert(toHighlight);
                    counter+=15+commentTokens[i][0].length;
                    while (!(toHighlight.wordBeginsAtIndex(commentTokens[i][1], counter) && (toHighlight.charAt(counter-1)!="\\" || (toHighlight.charAt(counter-1)+toHighlight.charAt(counter-2))=="\\\\")))
                    {
                        counter++;
                    }
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+commentTokens[i][1].length);
                    counter+=7+commentTokens[i][1].length;
                }
            }
            for (i=0; i<=syntaxTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(syntaxTokens[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+syntaxTokens[i].length)))
                {
                    isBeingHighlighted="syntax";
                    toHighlight=toHighlight.insertAtIndex("[color=#D100A5]", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+15+syntaxTokens[i].length);
                    counter+=syntaxTokens[i].length+22;
                    isBeingHighlighted="notsyntax";
                }
            }
            for (i=0; i<=tempVars.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(tempVars[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+tempVars[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("[color=#800080]", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+15+tempVars[i].length);
                    counter+=tempVars[i].length+22;
                }
            }
            for (i=0; i<=properties.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(properties[i], counter) && isLetter(toHighlight.charAt(counter-1)) && isLetter(toHighlight.charAt(counter+properties[i].length)))
                {
                    toHighlight=toHighlight.insertAtIndex("[color=#368288]", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+15+properties[i].length);
                    counter+=properties[i].length+22;
                }
            }
            for (i=0; i<=numericalTokens.length-1; i++)
            {
                if (toHighlight.charAt(counter)==numericalTokens[i])
                {
                    toHighlight=toHighlight.insertAtIndex("[color=#0000FF]", counter);
                    //alert(toHighlight);
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+16);
                    counter+=16+7;
                }
            }
            for (i=0; i<=blockTokens.length-1; i++)
            {
                if (toHighlight.wordBeginsAtIndex(blockTokens[i][0], counter))
                {
                    //alert(1);
                    toHighlight=toHighlight.insertAtIndex("[color=#FF0000]", counter);
                    //alert(toHighlight);
                    counter+=15+blockTokens[i][0].length;
                    while (!(toHighlight.wordBeginsAtIndex(blockTokens[i][1], counter) && (toHighlight.charAt(counter-1)!="\\" || (toHighlight.charAt(counter-1)+toHighlight.charAt(counter-2))=="\\\\")))
                    {
                        counter++;
                    }
                    toHighlight=toHighlight.insertAtIndex("[/color]", counter+blockTokens[i][1].length);
                    counter+=7+blockTokens[i][1].length;
                }
            }
            counter++;
        }
    }
    if (markup=="HTML")
    {
        var sideNums="";
        for (i=0; i<=toHighlight.split("<br/>").length - 1; i++)
        {
            sideNums=sideNums+i+"<br/>"
        }
        document.getElementById("preview").innerHTML=(toHighlight);
        if (document.getElementById("genBox").value)
        {
            toHighlight="<div style='overflow:scroll; white-space: nowrap; border-style:inset; border-width:2px; background-color:lavenderBlush; width:400px;'><div style='margin-top:5px; margin-left:5px; font-family:trebuchet ms; font-size:12px;'><b>Code:</b><br/><div style='float:left; font-family:monaco; font-size:10px; width:10px;'>"+sideNums+"</div><div style='float:left; width:350px; overflow:scroll; font-family:monaco; font-size:10px; border-style:solid; border-width:1px; border-color:blue; margin-left:5px;' onmouseover='this.select();'>"+toHighlight+"</div></div></div>";
        }
        document.getElementById("preview").innerHTML=(toHighlight);
    }
    document.getElementById("toHighlight").value=(toHighlight);
    document.getElementById("toHighlight").select();
}
function setLang(val)
{
    lang=val;
}
function setMarkup(val)
{
    markup=val;
}

Line numbers!  big_smile


Hardmaths-MacBook-Pro:~ Hardmath$ sudo make $(whoami) a sandwich

Offline

 
  • Index
  •  » Advanced Topics
  •  » JavaScript-based syntax highlighter (using BBCode) for Scratch forums

Board footer