Archive

Archive for the ‘Blogging tips’ Category

Syntax highlighting using SyntaxHighlighter and WordPress

September 9, 2012 Leave a comment

For a short summary of this post, see the "Short version of the tip" at the very end

WordPress itself does provide some source code highlighting features, which are based on the famous SyntaxHighlighter plugin from Alex Gorbatchev.

When using a blog at wordpress.com, then there is no option for installing the WP-plugin.

Instead wordpress itself does have already builtin some fuunctionality for highlighting code.

This is also based on SyntaxHighlighter.

WordPress expects this format for code to be formatted:

image    image

When using Windows LiveWriter, i found, that switching between Edit and Source code view mode, the Editor replaces the " into ", which then broke the highlighting functionality.

My workaround is, to use single quotes, like in the right picture above.

 

But then, the next problem is, how to copy/paste code from VS to Live writer.

Following Scott Hanselman’s post i’m using the "PreCode Snippet" plugin for Live Writer.

But inserting code will then look like this during editing in Live Writer:

image

Not bad, but not quite what i really want.

The reason, that SyntaxHighlighter is not yet in action is, that the shCore.js and shBrushCSharp.js files are not yet included. I did not find any way how to include scriptfiles from an external source, so my current workaround is, to force wordpress.com to include this files by using their syntax at the very end of any blogposting with one single line of dummy code like this:

image

 

This will include the .js files for SyntaxHighlighter and all code on the page will then look like this during editing in Live Writer:

image

but will then be reformatted to:

function DoIt()
{
    var x = DateTime.Now;
    var y = x.AddMinutes(2);
}

 

Other options which might be useful: (Note, that in this case an additional <pre></pre> must be applied…

image

will result into this:

 

<pre>function DoIt()
{
    var x = DateTime.Now;
    var y = x.AddMinutes(2);
}</pre>

<p>

 

 

Short version of the tip

So to make the long story short:

Use any CodePasting Live Writer plugin or manually place your code into a <pre></pre> tag.

Then make sure, that at least one occurrence of this line is in your posting:

(the . is needed as minimal placeholder for code content)

image

.

If you need some highlighting, then apply an additional line like this to your <pre></pre> surrounded code. But then, the <pre></pre> tags will be a visible part of your code….

Categories: Blogging tips