Within days of starting my tech blog I, like many other IT bloggers before me (and there will be many after me) wanted to include some code snippets - laid out nicely, with line numbers and keyword highlighting.
Although I found many tools online for this, they were either aimed at just one language or asked me to specify the language. So, lightbulb, why not assemble my own tool using a bit of jQuery, JavaScript and Regex that could be a little more intelligent than what already existed.
2. End goal Build an intuitive code formatter that can be grown by its users With some sample keywords from 5 languages, derive the language and apply styling 1st goal
3. Step 1: Break the problem down Photo by Douglas Woods http://www.flickr.com/photos/deerwooduk/1788483794/
4.
5. Step 2: One brick at a time Photo by Douglas Woods http://www.flickr.com/photos/deerwooduk/1788483794/ Photo by Takomabibelot http://www.flickr.com/photos/takomabibelot/2455018965/
7. Run a Regex match for each language and record the count var mArr = new Array(); for(var i=0; i<pArr.length; i++) { var m = (strIn.match(pArr[i])||[]).length; mArr[i] = new Array(); mArr[i][0] = pArr[i]; mArr[i][1] = m; }
8. Sort the array in descending order on match count mArr.sort(function(a,b){ return a[1] <= b[1]; });
9. Run a Regex replace, injecting formatting around identified keywords strIn = strIn.replace(mArr[0][0], '<br/><span style="color: green;font-weight: bold;">$1</span>'); strIn = strIn.replace(/({)/ig, '$1<br/> '); strIn = strIn.replace(/((^<br>)+)/,'');
10. Run a Regex replace, injecting line numbers to all lines var pLns = /(.*?)(<br>|$)/ig var lArr = strIn.match(pLns); strIn = ""; for(var i=0; i<lArr.length; i++) { var ln = lArr[i]; if(ln.length > 0) { var col = ((i%2)==1)? "fff" : "eee"; strIn += "<div style=amp;quot;background-color:#"+ col +"amp;quot;><div style=amp;quot;float:left;color:#666;amp;quot;>Line "+(i+1)+": </div><div><code>"+ln+"</code></div></div>"; } }
11. And that's version 1. So what next? > More keywords > More languages > More styling > More interaction > More contribution Wanna help? http://at-dpitt.blogspot.com/p/code-formatter-for-blogs.html