Edit: The latest version of the SyntaxHighlighter plugin, called SyntaxHighlighter Evolved, now supports version 2.0 and has built-in shortcode support which is way cooler than what I did here. :-)
I’ve been using SyntaxHighlighter to highlight code portions on my site for a while. Ok, I haven’t posted in seven months, but when I was posting more often, I did all of the code formatting by hand, and the capabilities were about 90% of what I wanted them to be. There were a few brushes that didn’t quite work right — (The perl brush, for instance, replaced all of the >’s with >. Thankfully, one of the user community stepped up and fixed it.) — but, on the whole, it really did a nice job. Posting said code, however, was a bit of a formatting pain and I was looking for a more convenient way to do so.
Scott Hanselman blogged that he uses a plug-in for Windows Live Writer called PreCode which works pretty well. Since I tend to use the web-based editor to craft 90% of my posts, that wasn’t as appealing to me, though I did play with it a bit and should I ever convert myself to WLW, I’d certainly go that route. Also, I had finally converted the site to use a plug-in for SyntaxHighlighter which has really excellent BBCode support rather than the manual javascript includes that I had before.
The end result was that, to save myself about 2-3 minutes per piece of code, I added a QuickTag to the wordpress HTML editor so that I could wrap code in the proper [code=''] block with a single click. To so requires editing {wordpress_install_dir}/wp-includes/js/quicktags.js :
1. Just past line 125, add:
edButtons[edButtons.length] =
new edButton('ed_sh'
,'syntax'
,''
,'{/code}' //Replace {} with [] here. SH munges '['/code']'
,'h'
);
2. A bit further down, in edShowButton(), add an additional else if() block:
else if (button.id == 'ed_sh') {
document.write('<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="edInsertSH(edCanvas, ' + i + ');" value="' + button.display + '" />');
}
3. Finally, you need to provide edInsertSH(). I just re-used edInsertLink() at what is now line 391:
function edInsertSH(myField, i, defaultValue) {
if (!defaultValue) {
defaultValue = 'sh';
}
if (!edCheckOpenTags(i)) {
var SH = prompt('Enter Syntax Type', defaultValue);
if (SH) {
edButtons[i].tagStart = "[code='" + SH + "']";
edInsertTag(myField, i);
}
}
else {
edInsertTag(myField, i);
}
}
If you happen to post a lot with a particular language, feel free to change the defaultValue to something more relevant. I chose sh because it's short. You could, alternatively, choose nothing.