Google
 

Sunday, January 4, 2009

Source Code Sucks

By which I mean, looking at source code on most websites sucks. The formatting is often broken, and there's rarely syntax highlighting. This post was prompted by a comment from an author of another blog that Blogger screws up source code. That's not the problem; the problem is that a lot of time and money has been poured into <insert favorite IDE>, while the same effort is not warranted to web browers and most websites.

However, with a little finesse, there is a solution that's easy to implement. You need:

  1. CSS for the code box and syntax highlighting
  2. A good find/replace JavaScript
  3. Code samples
Alex Gorbatchev of dreamprojections.com has created an excellent Syntax Highlighter script. (download link)

An Example

<html> <head> <link rel="stylesheet" type="text/css" href="dp.SyntaxHighlighter/Styles/SyntaxHighlighter.css" /> <script type="text/javascript" src="dp.SyntaxHighlighter/Scripts/shCore.js"></script> <script type="text/javascript" src="dp.SyntaxHighlighter/Scripts/shBrushCSharp.js"></script> <script type="text/javascript"> <!-- window.onload = function() { var codeBlocks = document.getElementsByName('csharp'); for(var i = 0; i < codeBlocks.length; i++) { codeBlocks[i].className = 'csharp'; } dp.SyntaxHighlighter.ClipboardSwf = 'dp.SyntaxHighlighter/Scripts/clipboard.swf'; dp.SyntaxHighlighter.HighlightAll('csharp',false,false,false,1,false); } //--> </script> </head> <body> <code name="csharp">using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { } } }</code> </body> </html>

This would produce:using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { } } }

The Google Code wiki for the JavaScript Syntax Highlighter shows how to modify settings of the code block through the class attribute. The same configuration can be done with the HighlightAll call, using the following parameters:HighlightAll(name, showGutter /* optional */, showControls /* optional */, collapseAll /* optional */, firstLine /* optional */, showColumns /* optional */)

No comments: