What are we facing?
I want to publish source code listings in my website. These listings should be easy to read, visually attractive and I don’t want to spend a lot of time formatting them.
The Solution
Using a syntax highlighting library can save you lots of time while also delivering very nicely formatted results.
There are several options to choose from, ranging from server-side options like Actipro’s CodeHighlighter(ASP.NET) or Javascript based options like Google’s SyntaxHighlighter.
Formatting code using these libraries is very easy, for example, to present a snipped of C# code you only have to type the following:
1. Reference the library
<link rel="stylesheet" type="text/css" href="css/SyntaxHighlighter.css"/>
<script language="javascript" src="js/shCore.js"></script>
<script language="javascript" src="js/shBrushCSharp.js"></script>
<script language="javascript" src="js/shBrushXml.js"></script>
2. Annotate the element that contains the source code listing with the programming language name:
<pre name="code" class="c-sharp">
public static int fact(int v)
{
if(v == 0)
{
return 1;
}
else
{
return fact(v-1)*v;
}
}
</pre>
3. Invoke the Syntax Highlighting script:
<script language="javascript">
dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf';
dp.SyntaxHighlighter.HighlightAll('code');
</script>
The final output looks like this:
Some external references
[advertisement] Try
Aggiorno for free, the assistant tool for web development you always wanted.