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

#1 2011-12-18 05:42:24

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

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

computeFunction: functionName of: aNumber
    "Return the result of computing the given mathematical function on the given number."

    'abs' = functionName ifTrue: [^ aNumber abs].
    'sqrt' = functionName ifTrue: [^ aNumber sqrt].
    'sin' = functionName ifTrue: [^ aNumber degreesToRadians sin].
    'cos' = functionName ifTrue: [^ aNumber degreesToRadians cos].
    'tan' = functionName ifTrue: [^ aNumber degreesToRadians tan].
    'asin' = functionName ifTrue: [^ (aNumber within: -1.0 and: 1.0) arcSin radiansToDegrees].
    'acos' = functionName ifTrue: [^ (aNumber within: -1.0 and: 1.0) arcCos radiansToDegrees].
    'atan' = functionName ifTrue: [^ aNumber arcTan radiansToDegrees].
   
    'ln' = functionName ifTrue: [^ aNumber ln].
    'log' = functionName ifTrue: [^ aNumber log].
    'e ^' = functionName ifTrue: [^ aNumber exp].
    '10 ^' = functionName ifTrue: [^ 10.0 raisedTo: aNumber].

    ^ 0

You can get an annotated code just like this! Just paste your code below (JS and Squeak only, so far), and I'll highlight the syntax with my JavaScript engine (Note: it cannot contain BBCode tags at the moment, and variables with syntax elements in their names get mis-highlighted). If you give me a list of some variables, they will show up purple. I even give HTML markups if you need a marked-up code for a website. Also, please tell me if you would like to contribute a library. Enjoy!

Known bugs:
Keywords within keywords are mishighlighted. Solved
BBCode is mishighlighted when retrieving BBCode. Solved
"<" causes errors when retrieving HTML. Solved

--

Supported platforms:
Input Code:
JavaScript [90% keywords]
Squeak [20% keywords]
HTML: [40% keywords]

Output Markup:
HTML
BBCode

To contribute a library, click here.

Last edited by Hardmath123 (2011-12-21 09:45:10)


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

Offline

 

#2 2011-12-18 07:11:52

rookwood101
Scratcher
Registered: 2011-07-29
Posts: 500+

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

Just some JS code I made for something:

Code:

var beenblue=new Array();
var beenorange=new Array();
var beengreen=new Array();
var dataurl=new Array();
var canvaselement=new Array();
var audioelement=new Array();
blues=0;
oranges=0;
greens=0;
countdownint=3;
gotallorange=false;
gotallblue=false;
gotallgreen=false;
levelplaying=false;
freeplaymode=false;
linesloaded=false;
intervalid=0;
audiotrack=0;
function amntimg() {
    if (document.body && document.body.offsetWidth) {
        winW = document.body.offsetWidth;
        winH = document.body.offsetHeight;
    }
    if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
        winW = document.documentElement.offsetWidth;
        winH = document.documentElement.offsetHeight;
    }
    if (window.innerWidth && window.innerHeight) {
        winW = window.innerWidth;
        winH = window.innerHeight;
    }
    winW=winW/127;
    winH=winH/128;
    winW=Math.floor(winW);
    winW=winW-1;
    winW=winW+1;
    winWs=winW;
    winH=Math.floor(winH);
    winH=winH-1;
    winHs=winH;
}

function imagegen() {
    colournum = 0;
    while (colournum<=3) {
    canvaselement[colournum] = document.createElement('canvas');
    canvaselement[colournum].width = 126;
    canvaselement[colournum].height = 128;
    context = canvaselement[colournum].getContext('2d');
    baseimagehelp = 'tester' + colournum
    baseimage = document.getElementById(baseimagehelp);
    context.drawImage(baseimage, 0, 0);
    context.font = '23px "Palatino Linotype", Palatino, "Book Antiqua"';
    context.textBaseline = 'top';
    context.fillstyle = '#000000';
    context.fillText(line1, 26, 24, 74);
    context.fillText(line2, 26, 50, 74);
    context.fillText(line3, 26, 76, 74);
    dataurl[colournum] = canvaselement[colournum].toDataURL();
    colournum = colournum+1;
    }
}

function fillscreen() {
    amntimg();
    idnumber=1;
    while (winH>0) {
        while (winW>0) {
            document.getElementById('main').innerHTML = document.getElementById('main').innerHTML + '<img id="' + idnumber + '" onMouseover="orangify(' + idnumber + ')" onClick="greenify(' + idnumber + ')" ondblClick="bluify(' + idnumber + ')" src="' + dataurl[0] + '">';
            winW=winW-1;
            beenblue[idnumber] = false;
            beenorange[idnumber] = false;
            beengreen[idnumber] = false;
            idnumber=idnumber+1;
        }
        document.getElementById('main').innerHTML = document.getElementById('main').innerHTML + '<br>';
        winW=winWs;
        winH=winH-1;
    }
}

function reloadit() {
    if (intervalid!=0) {
        stopinterval();
    }
    oranges=0;
    greens=0;
    blues=0;
    countdownint=3;
    gotallorange=false;
    gotallblue=false;
    gotallgreen=false;
    levelplaying=false;
    document.getElementById('main').innerHTML = '';
    document.getElementById('timeis').innerHTML = '0 Seconds';
    document.getElementById('oranges').innerHTML = oranges + ' Oranges Made';
    document.getElementById('greens').innerHTML = greens + ' Greens Made';
    document.getElementById('blues').innerHTML = blues + ' Blues Made';
    document.getElementById('gamecomplete').innerHTML = '';
    document.getElementById('levelcomplete').innerHTML = '';
    document.getElementById('start').innerHTML = 'Start Level';
    document.getElementById('start').setAttribute('onclick', 'startbutton()');
    document.getElementById('countdown').innerHTML = '';
}

function timeinterval() {
    seconds=0;
    document.getElementById('timeis').innerHTML = seconds + ' Seconds';
    intervalid=setInterval('timer()', 100);
}

function timer() {
    if (gotallorange && gotallblue && gotallgreen) {
        stopinterval();
        document.getElementById('levelcomplete').innerHTML = 'Level Complete!';
        document.getElementById('countdown').innerHTML = 'Level Complete!';
        audioelementchord.load();
        audioelementchord.play();
        levelplaying=false;
        if (amntlvl==levelb) {
            document.getElementById('gamecomplete').innerHTML = 'Game Complete!';
            document.getElementById('countdown').innerHTML = 'Game Complete!';
        }
        else {
            if (freeplaymode==false) {
            document.getElementById('start').innerHTML = 'Next Level';
            document.getElementById('start').setAttribute('onclick', 'nextlvl()');
            }
        }
    }
    if (oranges>=orangeneedint) {
        gotallorange=true;
    }
    if (greens>=greenneedint) {
        gotallgreen=true;
    }
    if (blues>=blueneedint) {
        gotallblue=true;
    }
    seconds=seconds+0.1;
    seconds=Math.round(seconds*10)/10;
    document.getElementById('timeis').innerHTML = seconds + ' Seconds';
}

function stopinterval() {
    window.clearInterval(intervalid);
}

function orangify(myid) {
if (countdownint==0) {
if (levelplaying==true) {
    if (document.getElementById(myid).src!=dataurl[1]) {
        if (beenorange[myid]==false) {
            
            document.getElementById(myid).src = dataurl[1];
            playbeep();
            oranges = oranges+1;
            beenorange[myid]= true;
            document.getElementById('oranges').innerHTML = oranges + ' Oranges Made';
        }
        else if (beenorange[myid]==true && freeplaymode==true) {
            
            document.getElementById(myid).src = dataurl[1];
            playbeep();
            oranges = oranges+1;
            beenorange[myid]= true;
            document.getElementById('oranges').innerHTML = oranges + ' Oranges Made';
        }
    }
}
}
}

function greenify(myid) {
if (countdownint==0) {
if (levelplaying==true) {
    if (document.getElementById(myid).src!=dataurl[2]) {
        if (beengreen[myid]==false) {
            
            document.getElementById(myid).src = dataurl[2];
            playbeep();
            greens = greens+1;
            beengreen[myid]=true;
            document.getElementById('greens').innerHTML = greens + ' Greens Made';
        }
        else if (beengreen[myid]==true && freeplaymode==true) {
            
            document.getElementById(myid).src = dataurl[2];
            playbeep();
            greens = greens+1;
            beengreen[myid]=true;
            document.getElementById('greens').innerHTML = greens + ' Greens Made';
        }
    }
}
}
}

function bluify(myid) {
if (countdownint==0) {
if (levelplaying==true) {
    if (document.getElementById(myid).src!=dataurl[3]) {
        if (beenblue[myid]==false) {
            
            document.getElementById(myid).src = dataurl[3];
            playbeep();
            blues = blues+1;
            beenblue[myid]=true;
            document.getElementById('blues').innerHTML = blues + ' Blues Made';
        }
        else if (beenblue[myid]==true && freeplaymode==true) {
            
            document.getElementById(myid).src = dataurl[3];
            playbeep();
            blues = blues+1;
            beenblue[myid]=true;
            document.getElementById('blues').innerHTML = blues + ' Blues Made';
        }
    }
}
}
}

function startbutton() {
    if (!levelplaying) {
        loadlines();
        reloadit();
        levelplaying=true;
        countdown();
        setuplevel(level);
        fillscreen();
    }
}

function countdown() {
    if (countdownint>0) {
        setTimeout('countdown1()', 1500);
        document.getElementById('countdown').innerHTML = countdownint;
    }
    if (countdownint==0) {
        document.getElementById('countdown').innerHTML = 'Go!';
        setTimeout('goremove()', 1000);
        if (freeplaymode==false) {
            timeinterval();
        }
    }
}

function countdown1() {
    countdownint=countdownint-1;
    countdown();
}

function goremove() {
    document.getElementById('countdown').innerHTML = '';
}

function freeplaybutton() {
    freeplaymode=true;
    if (!levelplaying) {
        reloadit();
        levelplaying=true;
        countdown();
        setuplevel(level);
        fillscreen();
    }
}

function loadstuff() {
    importlevels();
    audioelement[0] = document.createElement('audio');
    audioelement[0].setAttribute('src', 'audio/beep.wav');
    tempv=1;
    tempvp=2;
    while (tempv<=4) {
        audioelement[tempv] = document.createElement('audio');
        srcadd='audio/beep' + tempvp + '.wav';
        audioelement[tempv].setAttribute('src', srcadd);
        tempv=tempv+1;
        tempvp=tempvp+1;
    }
    audioelementchord = document.createElement('audio');
    audioelementchord.setAttribute('src', 'audio/chord.wav');
}

function loadlines() {
    if (linesloaded===false) {
    line1 = document.textlines.line1.value;
    line2 = document.textlines.line2.value;
    line3 = document.textlines.line3.value;
    linesloaded=true;
    imagegen();
    }
}

function limittext(limitfield, limitnum) {
    if (limitfield.value.length > limitnum) {
        limitfield.value = limitfield.value.substring(0, limitnum);
    }
}

function playbeep() {
        if (audiotrack==5) {
            audiotrack=0;
        }
        audioelement[audiotrack].load();
        audioelement[audiotrack].play();
        audiotrack=audiotrack+1;
}

http://i.imgur.com/zeIZW.png

Offline

 

#3 2011-12-18 09:17:13

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

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

rookwood101 wrote:

Just some JS code I made for something:
[...]

var beenblue=new Array();
var beenorange=new Array();
var beengreen=new Array();
var dataurl=new Array();
var canvaselement=new Array();
var audioelement=new Array();
blues=0;
oranges=0;
greens=0;
countdownint=3;
gotallorange=false;
gotallblue=false;
gotallgreen=false;
levelplaying=false;
freeplaymode=false;
linesloaded=false;
intervalid=0;
audiotrack=0;
function amntimg() {
    if (document.body && document.body.offsetWidth) {
        winW = document.body.offsetWidth;
        winH = document.body.offsetHeight;
    }
    if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
        winW = document.documentElement.offsetWidth;
        winH = document.documentElement.offsetHeight;
    }
    if (window.innerWidth && window.innerHeight) {
        winW = window.innerWidth;
        winH = window.innerHeight;
    }
    winW=winW/127;
    winH=winH/128;
    winW=Math.floor(winW);
    winW=winW-1;
    winW=winW+1;
    winWs=winW;
    winH=Math.floor(winH);
    winH=winH-1;
    winHs=winH;
}

function imagegen() {
    colournum = 0;
    while (colournum<=3) {
    canvaselement[colournum] = document.createElement('canvas');
    canvaselement[colournum].width = 126;
    canvaselement[colournum].height = 128;
    context = canvaselement[colournum].getContext('2d');
    baseimagehelp = 'tester' + colournum
    baseimage = document.getElementById(baseimagehelp);
    context.drawImage(baseimage, 0, 0);
    context.font = '23px "Palatino Linotype", Palatino, "Book Antiqua"';
    context.textBaseline = 'top';
    context.fillstyle = '#000000';
    context.fillText(line1, 26, 24, 74);
    context.fillText(line2, 26, 50, 74);
    context.fillText(line3, 26, 76, 74);
    dataurl[colournum] = canvaselement[colournum].toDataURL();
    colournum = colournum+1;
    }
}

function fillscreen() {
    amntimg();
    idnumber=1;
    while (winH>0) {
        while (winW>0) {
            document.getElementById('main').innerHTML = document.getElementById('main').innerHTML + '<img id="' + idnumber + '" onMouseover="orangify(' + idnumber + ')" onClick="greenify(' + idnumber + ')" ondblClick="bluify(' + idnumber + ')" src="' + dataurl[0] + '">';
            winW=winW-1;
            beenblue[idnumber] = false;
            beenorange[idnumber] = false;
            beengreen[idnumber] = false;
            idnumber=idnumber+1;
        }
        document.getElementById('main').innerHTML = document.getElementById('main').innerHTML + '<br>';
        winW=winWs;
        winH=winH-1;
    }
}

function reloadit() {
    if (intervalid!=0) {
        stopinterval();
    }
    oranges=0;
    greens=0;
    blues=0;
    countdownint=3;
    gotallorange=false;
    gotallblue=false;
    gotallgreen=false;
    levelplaying=false;
    document.getElementById('main').innerHTML = '';
    document.getElementById('timeis').innerHTML = '0 Seconds';
    document.getElementById('oranges').innerHTML = oranges + ' Oranges Made';
    document.getElementById('greens').innerHTML = greens + ' Greens Made';
    document.getElementById('blues').innerHTML = blues + ' Blues Made';
    document.getElementById('gamecomplete').innerHTML = '';
    document.getElementById('levelcomplete').innerHTML = '';
    document.getElementById('start').innerHTML = 'Start Level';
    document.getElementById('start').setAttribute('onclick', 'startbutton()');
    document.getElementById('countdown').innerHTML = '';
}

function timeinterval() {
    seconds=0;
    document.getElementById('timeis').innerHTML = seconds + ' Seconds';
    intervalid=setInterval('timer()', 100);
}

function timer() {
    if (gotallorange && gotallblue && gotallgreen) {
        stopinterval();
        document.getElementById('levelcomplete').innerHTML = 'Level Complete!';
        document.getElementById('countdown').innerHTML = 'Level Complete!';
        audioelementchord.load();
        audioelementchord.play();
        levelplaying=false;
        if (amntlvl==levelb) {
            document.getElementById('gamecomplete').innerHTML = 'Game Complete!';
            document.getElementById('countdown').innerHTML = 'Game Complete!';
        }
        else {
            if (freeplaymode==false) {
            document.getElementById('start').innerHTML = 'Next Level';
            document.getElementById('start').setAttribute('onclick', 'nextlvl()');
            }
        }
    }
    if (oranges>=orangeneedint) {
        gotallorange=true;
    }
    if (greens>=greenneedint) {
        gotallgreen=true;
    }
    if (blues>=blueneedint) {
        gotallblue=true;
    }
    seconds=seconds+0.1;
    seconds=Math.round(seconds*10)/10;
    document.getElementById('timeis').innerHTML = seconds + ' Seconds';
}

function stopinterval() {
    window.clearInterval(intervalid);
}

function orangify(myid) {
if (countdownint==0) {
if (levelplaying==true) {
    if (document.getElementById(myid).src!=dataurl[1]) {
        if (beenorange[myid]==false) {
           
            document.getElementById(myid).src = dataurl[1];
            playbeep();
            oranges = oranges+1;
            beenorange[myid]= true;
            document.getElementById('oranges').innerHTML = oranges + ' Oranges Made';
        }
        else if (beenorange[myid]==true && freeplaymode==true) {
           
            document.getElementById(myid).src = dataurl[1];
            playbeep();
            oranges = oranges+1;
            beenorange[myid]= true;
            document.getElementById('oranges').innerHTML = oranges + ' Oranges Made';
        }
    }
}
}
}

function greenify(myid) {
if (countdownint==0) {
if (levelplaying==true) {
    if (document.getElementById(myid).src!=dataurl[2]) {
        if (beengreen[myid]==false) {
           
            document.getElementById(myid).src = dataurl[2];
            playbeep();
            greens = greens+1;
            beengreen[myid]=true;
            document.getElementById('greens').innerHTML = greens + ' Greens Made';
        }
        else if (beengreen[myid]==true && freeplaymode==true) {
           
            document.getElementById(myid).src = dataurl[2];
            playbeep();
            greens = greens+1;
            beengreen[myid]=true;
            document.getElementById('greens').innerHTML = greens + ' Greens Made';
        }
    }
}
}
}

function bluify(myid) {
if (countdownint==0) {
if (levelplaying==true) {
    if (document.getElementById(myid).src!=dataurl[3]) {
        if (beenblue[myid]==false) {
           
            document.getElementById(myid).src = dataurl[3];
            playbeep();
            blues = blues+1;
            beenblue[myid]=true;
            document.getElementById('blues').innerHTML = blues + ' Blues Made';
        }
        else if (beenblue[myid]==true && freeplaymode==true) {
           
            document.getElementById(myid).src = dataurl[3];
            playbeep();
            blues = blues+1;
            beenblue[myid]=true;
            document.getElementById('blues').innerHTML = blues + ' Blues Made';
        }
    }
}
}
}

function startbutton() {
    if (!levelplaying) {
        loadlines();
        reloadit();
        levelplaying=true;
        countdown();
        setuplevel(level);
        fillscreen();
    }
}

function countdown() {
    if (countdownint>0) {
        setTimeout('countdown1()', 1500);
        document.getElementById('countdown').innerHTML = countdownint;
    }
    if (countdownint==0) {
        document.getElementById('countdown').innerHTML = 'Go!';
        setTimeout('goremove()', 1000);
        if (freeplaymode==false) {
            timeinterval();
        }
    }
}

function countdown1() {
    countdownint=countdownint-1;
    countdown();
}

function goremove() {
    document.getElementById('countdown').innerHTML = '';
}

function freeplaybutton() {
    freeplaymode=true;
    if (!levelplaying) {
        reloadit();
        levelplaying=true;
        countdown();
        setuplevel(level);
        fillscreen();
    }
}

function loadstuff() {
    importlevels();
    audioelement[0] = document.createElement('audio');
    audioelement[0].setAttribute('src', 'audio/beep.wav');
    tempv=1;
    tempvp=2;
    while (tempv<=4) {
        audioelement[tempv] = document.createElement('audio');
        srcadd='audio/beep' + tempvp + '.wav';
        audioelement[tempv].setAttribute('src', srcadd);
        tempv=tempv+1;
        tempvp=tempvp+1;
    }
    audioelementchord = document.createElement('audio');
    audioelementchord.setAttribute('src', 'audio/chord.wav');
}

function loadlines() {
    if (linesloaded===false) {
    line1 = document.textlines.line1.value;
    line2 = document.textlines.line2.value;
    line3 = document.textlines.line3.value;
    linesloaded=true;
    imagegen();
    }
}

function limittext(limitfield, limitnum) {
    if (limitfield.value.length > limitnum) {
        limitfield.value = limitfield.value.substring(0, limitnum);
    }
}

function playbeep() {
        if (audiotrack==5) {
            audiotrack=0;
        }
        audioelement[audiotrack].load();
        audioelement[audiotrack].play();
        audiotrack=audiotrack+1;
}

Last edited by Hardmath123 (2011-12-18 09:38:10)


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

Offline

 

#4 2011-12-18 11:32:08

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

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

function orangify(myid) {

It's picking up the "if" token inside a function name, which I'm not sure is what you want.


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

Offline

 

#5 2011-12-19 06:04:36

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

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

blob8108 wrote:

function orangify(myid) {

It's picking up the "if" token inside a function name, which I'm not sure is what you want.

Err... yeah. I just patched it up so that words in the middle wouldn't be caught (before), but words in front are still caught (forgot[/b]). I'm getting to it.


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

Offline

 

#6 2011-12-19 06:43:06

rookwood101
Scratcher
Registered: 2011-07-29
Posts: 500+

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

Hardmath123 wrote:

blob8108 wrote:

function orangify(myid) {

It's picking up the "if" token inside a function name, which I'm not sure is what you want.

Err... yeah. I just patched it up so that words in the middle wouldn't be caught (before), but words in front are still caught (forgot[/b]). I'm getting to it.

Still, that's pretty good  smile .


http://i.imgur.com/zeIZW.png

Offline

 

#7 2011-12-19 07:29:47

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

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

rookwood101 wrote:

Hardmath123 wrote:

blob8108 wrote:


It's picking up the "if" token inside a function name, which I'm not sure is what you want.

Err... yeah. I just patched it up so that words in the middle wouldn't be caught (before), but words in front are still caught (forgot[/b]). I'm getting to it.

Still, that's pretty good  smile .

Thanks!


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

Offline

 

#8 2011-12-19 08:01:21

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

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

An hour of debugging, a brilliant idea, and a terrible scope error later:

var beenblue=new Array();
var beenorange=new Array();
var beengreen=new Array();
var dataurl=new Array();
var canvaselement=new Array();
var audioelement=new Array();
blues=0;
oranges=0;
greens=0;
countdownint=3;
gotallorange=false;
gotallblue=false;
gotallgreen=false;
levelplaying=false;
freeplaymode=false;
linesloaded=false;
intervalid=0;
audiotrack=0;
function amntimg() {
    if (document.body && document.body.offsetWidth) {
        winW = document.body.offsetWidth;
        winH = document.body.offsetHeight;
    }
    if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
        winW = document.documentElement.offsetWidth;
        winH = document.documentElement.offsetHeight;
    }
    if (window.innerWidth && window.innerHeight) {
        winW = window.innerWidth;
        winH = window.innerHeight;
    }
    winW=winW/127;
    winH=winH/128;
    winW=Math.floor(winW);
    winW=winW-1;
    winW=winW+1;
    winWs=winW;
    winH=Math.floor(winH);
    winH=winH-1;
    winHs=winH;
}

function imagegen() {
    colournum = 0;
    while (colournum<=3) {
    canvaselement[colournum] = document.createElement('canvas');
    canvaselement[colournum].width = 126;
    canvaselement[colournum].height = 128;
    context = canvaselement[colournum].getContext('2d');
    baseimagehelp = 'tester' + colournum
    baseimage = document.getElementById(baseimagehelp);
    context.drawImage(baseimage, 0, 0);
    context.font = '23px "Palatino Linotype", Palatino, "Book Antiqua"';
    context.textBaseline = 'top';
    context.fillstyle = '#000000';
    context.fillText(line1, 26, 24, 74);
    context.fillText(line2, 26, 50, 74);
    context.fillText(line3, 26, 76, 74);
    dataurl[colournum] = canvaselement[colournum].toDataURL();
    colournum = colournum+1;
    }
}

function fillscreen() {
    amntimg();
    idnumber=1;
    while (winH>0) {
        while (winW>0) {
            document.getElementById('main').innerHTML = document.getElementById('main').innerHTML + '<img id="' + idnumber + '" onMouseover="orangify(' + idnumber + ')" onClick="greenify(' + idnumber + ')" ondblClick="bluify(' + idnumber + ')" src="' + dataurl[0] + '">';
            winW=winW-1;
            beenblue[idnumber] = false;
            beenorange[idnumber] = false;
            beengreen[idnumber] = false;
            idnumber=idnumber+1;
        }
        document.getElementById('main').innerHTML = document.getElementById('main').innerHTML + '<br>';
        winW=winWs;
        winH=winH-1;
    }
}

function reloadit() {
    if (intervalid!=0) {
        stopinterval();
    }
    oranges=0;
    greens=0;
    blues=0;
    countdownint=3;
    gotallorange=false;
    gotallblue=false;
    gotallgreen=false;
    levelplaying=false;
    document.getElementById('main').innerHTML = '';
    document.getElementById('timeis').innerHTML = '0 Seconds';
    document.getElementById('oranges').innerHTML = oranges + ' Oranges Made';
    document.getElementById('greens').innerHTML = greens + ' Greens Made';
    document.getElementById('blues').innerHTML = blues + ' Blues Made';
    document.getElementById('gamecomplete').innerHTML = '';
    document.getElementById('levelcomplete').innerHTML = '';
    document.getElementById('start').innerHTML = 'Start Level';
    document.getElementById('start').setAttribute('onclick', 'startbutton()');
    document.getElementById('countdown').innerHTML = '';
}

function timeinterval() {
    seconds=0;
    document.getElementById('timeis').innerHTML = seconds + ' Seconds';
    intervalid=setInterval('timer()', 100);
}

function timer() {
    if (gotallorange && gotallblue && gotallgreen) {
        stopinterval();
        document.getElementById('levelcomplete').innerHTML = 'Level Complete!';
        document.getElementById('countdown').innerHTML = 'Level Complete!';
        audioelementchord.load();
        audioelementchord.play();
        levelplaying=false;
        if (amntlvl==levelb) {
            document.getElementById('gamecomplete').innerHTML = 'Game Complete!';
            document.getElementById('countdown').innerHTML = 'Game Complete!';
        }
        else {
            if (freeplaymode==false) {
            document.getElementById('start').innerHTML = 'Next Level';
            document.getElementById('start').setAttribute('onclick', 'nextlvl()');
            }
        }
    }
    if (oranges>=orangeneedint) {
        gotallorange=true;
    }
    if (greens>=greenneedint) {
        gotallgreen=true;
    }
    if (blues>=blueneedint) {
        gotallblue=true;
    }
    seconds=seconds+0.1;
    seconds=Math.round(seconds*10)/10;
    document.getElementById('timeis').innerHTML = seconds + ' Seconds';
}

function stopinterval() {
    window.clearInterval(intervalid);
}

function orangify(myid) {
if (countdownint==0) {
if (levelplaying==true) {
    if (document.getElementById(myid).src!=dataurl[1]) {
        if (beenorange[myid]==false) {
           
            document.getElementById(myid).src = dataurl[1];
            playbeep();
            oranges = oranges+1;
            beenorange[myid]= true;
            document.getElementById('oranges').innerHTML = oranges + ' Oranges Made';
        }
        else if (beenorange[myid]==true && freeplaymode==true) {
           
            document.getElementById(myid).src = dataurl[1];
            playbeep();
            oranges = oranges+1;
            beenorange[myid]= true;
            document.getElementById('oranges').innerHTML = oranges + ' Oranges Made';
        }
    }
}
}
}

function greenify(myid) {
if (countdownint==0) {
if (levelplaying==true) {
    if (document.getElementById(myid).src!=dataurl[2]) {
        if (beengreen[myid]==false) {
           
            document.getElementById(myid).src = dataurl[2];
            playbeep();
            greens = greens+1;
            beengreen[myid]=true;
            document.getElementById('greens').innerHTML = greens + ' Greens Made';
        }
        else if (beengreen[myid]==true && freeplaymode==true) {
           
            document.getElementById(myid).src = dataurl[2];
            playbeep();
            greens = greens+1;
            beengreen[myid]=true;
            document.getElementById('greens').innerHTML = greens + ' Greens Made';
        }
    }
}
}
}

function bluify(myid) {
if (countdownint==0) {
if (levelplaying==true) {
    if (document.getElementById(myid).src!=dataurl[3]) {
        if (beenblue[myid]==false) {
           
            document.getElementById(myid).src = dataurl[3];
            playbeep();
            blues = blues+1;
            beenblue[myid]=true;
            document.getElementById('blues').innerHTML = blues + ' Blues Made';
        }
        else if (beenblue[myid]==true && freeplaymode==true) {
           
            document.getElementById(myid).src = dataurl[3];
            playbeep();
            blues = blues+1;
            beenblue[myid]=true;
            document.getElementById('blues').innerHTML = blues + ' Blues Made';
        }
    }
}
}
}

function startbutton() {
    if (!levelplaying) {
        loadlines();
        reloadit();
        levelplaying=true;
        countdown();
        setuplevel(level);
        fillscreen();
    }
}

function countdown() {
    if (countdownint>0) {
        setTimeout('countdown1()', 1500);
        document.getElementById('countdown').innerHTML = countdownint;
    }
    if (countdownint==0) {
        document.getElementById('countdown').innerHTML = 'Go!';
        setTimeout('goremove()', 1000);
        if (freeplaymode==false) {
            timeinterval();
        }
    }
}

function countdown1() {
    countdownint=countdownint-1;
    countdown();
}

function goremove() {
    document.getElementById('countdown').innerHTML = '';
}

function freeplaybutton() {
    freeplaymode=true;
    if (!levelplaying) {
        reloadit();
        levelplaying=true;
        countdown();
        setuplevel(level);
        fillscreen();
    }
}

function loadstuff() {
    importlevels();
    audioelement[0] = document.createElement('audio');
    audioelement[0].setAttribute('src', 'audio/beep.wav');
    tempv=1;
    tempvp=2;
    while (tempv<=4) {
        audioelement[tempv] = document.createElement('audio');
        srcadd='audio/beep' + tempvp + '.wav';
        audioelement[tempv].setAttribute('src', srcadd);
        tempv=tempv+1;
        tempvp=tempvp+1;
    }
    audioelementchord = document.createElement('audio');
    audioelementchord.setAttribute('src', 'audio/chord.wav');
}

function loadlines() {
    if (linesloaded===false) {
    line1 = document.textlines.line1.value;
    line2 = document.textlines.line2.value;
    line3 = document.textlines.line3.value;
    linesloaded=true;
    imagegen();
    }
}

function limittext(limitfield, limitnum) {
    if (limitfield.value.length > limitnum) {
        limitfield.value = limitfield.value.substring(0, limitnum);
    }
}

function playbeep() {
        if (audiotrack==5) {
            audiotrack=0;
        }
        audioelement[audiotrack].load();
        audioelement[audiotrack].play();
        audiotrack=audiotrack+1;
}


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

Offline

 

#9 2011-12-19 11:20:29

rookwood101
Scratcher
Registered: 2011-07-29
Posts: 500+

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

yay! All you've got to do now is make it do it in real time in-browser whilst editing.


http://i.imgur.com/zeIZW.png

Offline

 

#10 2011-12-20 03:22:17

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

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

rookwood101 wrote:

yay! All you've got to do now is make it do it in real time in-browser whilst editing.

I does, but only on my HTML page. I'll distribute it a bit later.

EDIT: In your code, what does "been" mean? "Bean", misspelled?

Last edited by Hardmath123 (2011-12-20 03:22:50)


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

Offline

 

#11 2011-12-20 05:02:33

rookwood101
Scratcher
Registered: 2011-07-29
Posts: 500+

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

Hardmath123 wrote:

rookwood101 wrote:

yay! All you've got to do now is make it do it in real time in-browser whilst editing.

I do, but only on my HTML page. I'll distribute it a bit later.

EDIT: In your code, what does "been" mean? "Bean", misspelled?

It's used in tandem with the different colours to store an array of booleans. As in, "Has it been blue yet?"

To be honest, the code is pretty messy. I'm not the best at javascript ever  smile

Last edited by rookwood101 (2011-12-20 05:05:13)


http://i.imgur.com/zeIZW.png

Offline

 

#12 2011-12-20 07:53:15

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

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

rookwood101 wrote:

Hardmath123 wrote:

rookwood101 wrote:

yay! All you've got to do now is make it do it in real time in-browser whilst editing.

I do, but only on my HTML page. I'll distribute it a bit later.

EDIT: In your code, what does "been" mean? "Bean", misspelled?

It's used in tandem with the different colours to store an array of booleans. As in, "Has it been blue yet?"

To be honest, the code is pretty messy. I'm not the best at javascript ever  smile

Ahh... I was wondering what it meant.
Anyway, if I could give you one suggestion, it would be to indent your code and add comments. It makes a huge difference when you revisit it a month later.


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

Offline

 

#13 2011-12-20 09:15:51

rookwood101
Scratcher
Registered: 2011-07-29
Posts: 500+

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

Hardmath123 wrote:

rookwood101 wrote:

Hardmath123 wrote:


I do, but only on my HTML page. I'll distribute it a bit later.

EDIT: In your code, what does "been" mean? "Bean", misspelled?

It's used in tandem with the different colours to store an array of booleans. As in, "Has it been blue yet?"

To be honest, the code is pretty messy. I'm not the best at javascript ever  smile

Ahh... I was wondering what it meant.
Anyway, if I could give you one suggestion, it would be to indent your code and add comments. It makes a huge difference when you revisit it a month later.

Looks pretty indented to me, but yes I probably should indent it, me and my programming bad habits.


http://i.imgur.com/zeIZW.png

Offline

 

#14 2011-12-20 10:47:24

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

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

rookwood101 wrote:

Hardmath123 wrote:

rookwood101 wrote:


It's used in tandem with the different colours to store an array of booleans. As in, "Has it been blue yet?"

To be honest, the code is pretty messy. I'm not the best at javascript ever  smile

Ahh... I was wondering what it meant.
Anyway, if I could give you one suggestion, it would be to indent your code and add comments. It makes a huge difference when you revisit it a month later.

Looks pretty indented to me, but yes I probably should indent it, me and my programming bad habits.

Ok, sorry, I meant indent using "tab".


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

Offline

 

#15 2011-12-21 04:08:51

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

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

Give. Me. The. Link.
So cool.

Offline

 

#16 2011-12-21 05:02:30

rookwood101
Scratcher
Registered: 2011-07-29
Posts: 500+

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

Hardmath123 wrote:

rookwood101 wrote:

Hardmath123 wrote:


Ahh... I was wondering what it meant.
Anyway, if I could give you one suggestion, it would be to indent your code and add comments. It makes a huge difference when you revisit it a month later.

Looks pretty indented to me, but yes I probably should indent it, me and my programming bad habits.

Ok, sorry, I meant indent using "tab".

Oh right, I did, but I don't think the scratch website likes using tabs. In fact, wherever I upload it to, unless I upload it as a file (for example pastebin.com) it converts the tabs to spaces.


http://i.imgur.com/zeIZW.png

Offline

 

#17 2011-12-21 05:36:32

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

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

rookwood101 wrote:

Hardmath123 wrote:

rookwood101 wrote:


Looks pretty indented to me, but yes I probably should indent it, me and my programming bad habits.

Ok, sorry, I meant indent using "tab".

Oh right, I did, but I don't think the scratch website likes using tabs. In fact, wherever I upload it to, unless I upload it as a file (for example pastebin.com) it converts the tabs to spaces.

Ah... that explains why my auto-indent wasn't working on the website...

@scimonster: When I'm done with it, I'll give out the .js and .html files.


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

Offline

 

#18 2011-12-21 08:37:56

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

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

Hardmath123 wrote:

rookwood101 wrote:

Hardmath123 wrote:


Ok, sorry, I meant indent using "tab".

Oh right, I did, but I don't think the scratch website likes using tabs. In fact, wherever I upload it to, unless I upload it as a file (for example pastebin.com) it converts the tabs to spaces.

Ah... that explains why my auto-indent wasn't working on the website...

@scimonster: When I'm done with it, I'll give out the .js and .html files.

Aw, I don't want to wait.  sad  And I'm not going to go develop my own, because I'm already working on a bit JS project.  tongue

Offline

 

#19 2011-12-21 09:03:21

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

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

Testing HTML:

<script type="text/javascript" src="Highlighter.js"></script>
<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
<!--123-->


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

Offline

 

#20 2011-12-21 09:14:39

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

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

Hardmath123 wrote:

Testing HTML:

<script type="text/javascript" src="Highlighter.js"></script>
<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
<!--123-->

Wow, that is a lot of code it produces. First time I've looked at it.  tongue
Haha, now I have the basic HTML page structure! Useless without Highlighter.js.  tongue  TBH, if I had the JS one, I could probably reconstruct the HTML on my own. XD

Last edited by scimonster (2011-12-21 09:42:35)

Offline

 

#21 2011-12-21 09:36:06

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

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

scimonster wrote:

Hardmath123 wrote:

Testing HTML:

<script type="text/javascript" src="Highlighter.js"></script>
<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
<!--123-->

Wow, that is a lot of code it produces. First time I've looked at it.  tongue
Haha, now I have the basic HTML page structure! Useless without Highlighter.js.  tongue  TBH, if I had the JS one, I could probably reconstruct the HTML n my own. XD

'k, if you really want it, I'll give it to you. Just a sec...


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

Offline

 

#22 2011-12-21 09:43:27

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

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

Debugging HTML highlighting, still buggy:

<!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>

Last edited by Hardmath123 (2011-12-21 09:47:22)


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

Offline

 

#23 2011-12-21 10:12:04

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

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

Highlighter.js:

var lang="JavaScript";
var markup="HTML";
function isLetter(char)
{
    if(lang=="HTML")
    {
        return true;
    }
    var i;
    for (i=0; i<=51; i++)
    {
        if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(i)==char)
        {
            return false;
        }
    }
    return true;
}
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"];
    }
    /*
    if (lang=="HTML")
    {
        var tempTokens=["html", "head", "body", "!DOCTYPE", "p", "div", "span", "a", "script", "style", "input", "button", "textarea", "br", "hr", "canvas", "abbr", "/", ""];
        for (i=0; i<tempTokens.length; i++)
        {
            syntaxTokens.push("<"+tempTokens[i]);
            syntaxTokens.push(tempTokens[i]+">");
        }
        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"];
        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;");
        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](");
        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+=8+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+15+8;
                }
            }
            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+15+8;
                }
            }
            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+15+8;
                }
            }
            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+=8+blockTokens[i][1].length;
                }
            }
            counter++;
        }
    }
    if (markup=="HTML")
    {
        document.getElementById("preview").innerHTML sad "<span style='font-family:monaco; font-size:10pt'>"+toHighlight+"</span>");
    }
    document.getElementById("toHighlight").value=(toHighlight);
    document.getElementById("toHighlight").select();
}
function setLang(val)
{
    lang=val;
}
function setMarkup(val)
{
    markup=val;
}

Hey, you asked for it.  tongue

Code:

// CONDENSED //
var lang="JavaScript";
var markup="HTML";
function isLetter(char)
{
    if(lang=="HTML")
    {
        return true;
    }
    var i;
    for (i=0; i<=51; i++)
    {
        if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(i)==char)
        {
            return false;
        }
    }
    return true;
}
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"];
    }
    /*
    if (lang=="HTML")
    {
        var tempTokens=["html", "head", "body", "!DOCTYPE", "p", "div", "span", "a", "script", "style", "input", "button", "textarea", "br", "hr", "canvas", "abbr", "/", ""];
        for (i=0; i<tempTokens.length; i++)
        {
            syntaxTokens.push("<"+tempTokens[i]);
            syntaxTokens.push(tempTokens[i]+">");
        }
        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"];
        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;");
        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](");
        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+=8+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+15+8;
                }
            }
            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+15+8;
                }
            }
            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+15+8;
                }
            }
            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+=8+blockTokens[i][1].length;
                }
            }
            counter++;
        }
    }
    if (markup=="HTML")
    {
        document.getElementById("preview").innerHTML=("<span style='font-family:monaco; font-size:10pt'>"+toHighlight+"</span>");
    }
    document.getElementById("toHighlight").value=(toHighlight);
    document.getElementById("toHighlight").select();
}
function setLang(val)
{
    lang=val;
}
function setMarkup(val)
{
    markup=val;
}

EDT: Great, I got the code box to contain boldened text. What is the world coming to?

Last edited by Hardmath123 (2011-12-21 10:18:45)


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

Offline

 

#24 2011-12-21 11:05:23

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

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

Now just get the code box to contain different colored text.  tongue

Can you make a highlighter for Python too?  tongue

Offline

 

#25 2011-12-21 11:51:19

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

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

Hardmath123 wrote:

Highlighter.js:

if (markup=="BBC")
    {
        toHighlight=toHighlight.replace(/\[/g, "[[i][/i]").replace(/\)\)/g, ")[i][/i])").replace(/\(\(/g, "([i][/i](");
        while (counter<=toHighlight.length-1)
        {

Hey, you asked for it.  tongue

EDT: Great, I got the code box to contain boldened text. What is the world coming to?

LOL I did.
Here's a patch for that off the top of my head, to remove the bold text from code. Just duplicate

.replace(/\)\)/g, ")[i][/i])").replace(/\(\(/g, "([i][/i](")

That should take care of any )))s. For the smilies it's a bit longer, but whatever. I'm sure you can figure it out.  tongue

EDIT: Just used it, it really is pretty powerful.  big_smile

Last edited by scimonster (2011-12-21 12:03:17)

Offline

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

Board footer