Syntax highlighting with javascript and css

Just found a great product dp.SyntaxHighlighter. Its name is selfdescriptive. Using javascript and css it lets your code snippets look very neat in browser window. It already supports major popular languages, here's the list of supported languages as of version 1.4.1 (released on: September 19th, 2006):

  • css
  • c#, c-sharp, csharp
  • c, cpp, c++
  • vb, vb.net
  • delphi, pascal
  • js, jscript, javascript
  • php
  • py, python
  • ruby
  • sql
  • xml, xhtml, xslt, html, xhtml

To setup it on your site, download and put under your javascript folder everything from Scripts folder and copy Styles/SyntaxHighlighter.css into your css folder. Then you have to add links to these files on your pages:

In the head section you can load only the languages you need (shBrush<lang>.js files). After this, just put your code within textarea element, give it a name "code" and assign it a class corresponding to your language. For example:

<textarea name="code" class="python"  rows="10" cols="100">

def print_hello():
    print "hello world"

if __name__ == "__main__":
    print_hello()

</textarea>

This should look similar to the following snippet in a browser window:

Also, there are some controls available:

  • nogutter
    Will display no gutter.
  • nocontrols
    Will display no controls at the top.
  • collapse
    Will collapse the block by default.
  • firstline[value]
    Will begin line count at value. Default value is 1.
  • showcolumns
    Will show row columns in the first line.

They can be appended to the class name, e.g. class="python:nogutter:nocontrols"