In my blog I frequently share code for little projects in Processing & Arduino. It’s always bothered me to look at the black and white text which, in comparison to the beautifully colored code in various editors, is quite a strain to read. I considered a few ways to do this, primarily client side with JavaScript, server side with PHP, or something pre-formatted in any language.
I decided to write a script to add in the necessary HTML to color the code, which I could then paste into my site. Although this does add a fair amount more to the size of the HTML files on the site I decided it was the best way to go. A server side script, probably built into a WordPress Plugin, would be nice and easy to use, but it would be run every time the page was loaded and would be a load on the server. A JavaScript highlighter would also work well, but it would still be a large script anyway and it would add the hassle of browser inconsistencies and run time on slower browsers.
Since I was building this script I wanted to make it available to others. The Processing and Arduino communities, which the script is built for, are both great about sharing code, and this will make sharing just a little bit easier.
The script is built into a simple site at www.anthonymattox.com/code_formatter. You can paste your code into the page, adjust the settings, and format it. The script returns the HTML and a chunk of CSS based on the styles you selected on the first page. Paste the HTML into your site and either add the given CSS or use it as a model to write your own.
In my blog its styled to look something like this. Unfortunately it’s still black in rss readers.
processing code
code formatterSample Processing Code
/* sample processing code */ /* analog clock */ PVector mid; float sc, mn, hr, s, m, h; void setup() { background(20); size(400,400); noFill(); stroke(200); smooth(); frameRate(1); mid=new PVector(width/2,height/2,0); } void draw() { background(0); s=float(second()); m=float(minute()); h=float(hour()); sc=(s-15)/60*TWO_PI; mn=(m-15)/60*TWO_PI; hr=(h-3)/12*TWO_PI+mn/12; strokeWeight(2); stroke(200,0,0); line(mid.x,mid.y,mid.x+100*cos(sc),mid.y+100*sin(sc)); stroke(200); line(mid.x,mid.y,mid.x+110*cos(mn),mid.y+110*sin(mn)); strokeWeight(4); line(mid.x,mid.y,mid.x+60*cos(hr),mid.y+60*sin(hr)); stroke(50); ellipse(mid.x,mid.y,240,240); }