The Syntax Highlighter - Part 2

In the first part of this series I went over how I about starting my syntax highlighting plug-in for this website. I left of with a joined regular expression used to match all elements in my code string which match any of my definition. I wrap each found definition in span with a class of found. At this point point, we dont care which of our definitions are being hit, just that one of them.

// code string
if (x == y) { return x; }  

Becomes

<span class="found">// code string</span><br /><span class="found">if</span> <span style="line-height: 1.42857143;"><span style="background-color: transparent; color: inherit; font-size: inherit; line-height: 1.42857143;">(</span>x </span><span style="line-height: 1.42857143;"><span class="found">==</span> y</span><span style="line-height: 1.42857143;"><span class="found">)</span> </span><span style="line-height: 1.42857143;"><span style="line-height: 1.42857143; background-color: transparent; color: inherit; font-size: inherit;">{</span> </span><span style="line-height: 1.42857143;"><span class="found">return</span> x; </span><span style="line-height: 1.42857143;"><span class="found">}</span></span  

So now we have a code string which contains alot of span tags. We can now start using CSS to change the styles of our selected elements.

.found { color: #0ff; }

Now we have a bunch of highlighted code segments. But thats not exactly helpfull to anyone like this. You'll note that in our JSON string we have a class set for each of our definitions. Applying these other classes is relatively simple now. Using jQuery, we can easily iterate over each individual span.found tag, we can then use a custom function with our definition Regular Expressions to determing which of our definition classes we are suppose to use.

$('span.found').each(function iterateFound() {
    $(this).removeClass('found').addClass(fnGetDefinitionClass($(this),_patterns));
});

fnGetDefinitionClass(_block,_patterns) {  
    for (var j in _patterns) {
        var _regEx = new RegExp(_patterns[j].pattern,"gi");
        if (_block.html().match(_regEx)) {
            return _patterns[j].class;
        }
    }
    return "found";
}

Once we do that, we just need to adjust our style sheet.

.found { color: #0ff; }
.constant { color: #f00; }
.operator { color: #0f0; }
.comment { color: #00f; }

Thats that, we have now have a simple working Syntax Highlighter. Next Up! lets turn it into a jQuery Plugin.