Thursday, October 08, 2009

Syntax Highlighting in Your Blog

A few years ago I used to use Apple's Pages program to do my blogs. Pages would allow me to save a document as HTML, much the same way that Word would. So I would set off constructing my blog in Pages much like I would a normal document. I was able to copy code from Eclipse into Pages and it would preserve the formatting and colors. Now the HTML wasn't perfect and needed a tiny bit of work for a seamless transfer into Blogger. I created a small Ruby script to strip out the un-needed things and add in the other bits. In the end I was able to save my document as HTML, run my Ruby script against it and paste the resulting text straight into blogger and it would look just as it had in Pages.

Well... Apple removed that feature from Pages and I was stuck looking for other options. I was searching tonight and noticed a few people using the demo of GeSHi and editing the resulting page source etc. That was a bit more work than I was willing to do.

I remembered a while back that Google Docs would also preserve RTF when pasting. So I embarked on a test. I copied some source code from XCode and pasted it into Google Docs. Then I did a quick look at the DOM and found exactly the piece I wanted. I then added this bit in the URL(as one line)


And copied the result from the pop-up and pasted it into my blog. The only caveat is the editor you're copying from needs to copy your snippet as RTF

(I used this to generate the above javascript)


Anonymous said...

Have you tried using one of the js syntax highlighters? Or do they not do as good of a job as the highlighting in Eclipse?

I use this one and it seems to work well:

I just html-escape the code, paste it in, and let the js handle the highlighting.

jr said...

Nice! Thanks for that tip. I'll have to try that option out on my next post :)