As a programmer you often want to share some piece of nice code by placing it in your post on the blog.
You can just wrap it in <code> or <pre> tags and play with CSS to make it more readable. But it is not enough usually. Many of us are accustomed to have code highlighting for better readability.
There are server and client side solutions, ASP, PHP or JS based. You can choose one best for you.
As a WordPress user, you may also be interested in easy integration via WP plug-in (GoSHi wrapper).
I have used the following criteria in my search:
- it should be easy to integrate in WordPress, do not use tags and structures which will violate XHTML compliance requirements (I prefer to have my pages to pass W3C XHTML validation).
- it should be easy to use within BBcode-like WYSIWYG editor
- have some basic Copy/Paste/Print support
I did not much care about server or client side implementation.
My choice was a SyntaxHighlighter by Alex Gorbatchev. Few things with original code were:
- no out of the box support for WordPress
- tag syntax used by default was breaking W3C validation
Ok, choice was to find someone already adopted it or create my own plug-in. Lucky for me there was one already. It was using BBCode to wrap the snippet but it did not address an issue of the invalid tags.
But it was easy to address also – in original code “name” is used to specify that <pre> does represent the code snippet.
Since I am not using this tag for anything else simple replacement in the source code would do the trick:
- download and install plug-in
- locate shCore.js and look for the following line FindTagsByName(elements, name, ‘pre’);
- replace it with FindTagsByName(elements, null, ‘pre’);
- save, upload
- Update (01/05/2009): With release of latest plug-in version, one more adjustment is required in the WP plugin itself:
- Locate and Open syntaxhighlighter.php
- Locate line “$content = str_replace( $match, ‘<pre name=”code” class= … “
- If you are using any WP cache plugins, clear your cache
- add code into your blog (this is how it is seen in the editor)
and you will get it displayed nicely like shown here.
PS. what you also would get is an ability to print/copy/view the code in easy and convinient way.