Friday, July 8, 2011

Embedding code with SyntaxHighlighter

Alex Gorbatchev's SyntaxHighlighter is the best thing around for adding syntax highlighting to code embedded into your blogs. Readers see line numbers but can easily cut-and-paste with or without those often pesky line numbers.

After you have all the necessary JavaScript and CSS files loaded into your web-page (see below for details on that) you have two choices for wrapping your source code. The "pre" method is necessary for CSS feeds, but the "script/CDATA" method handles embedded HTML tags without escaping them. The title is optional for both.

<script type="syntaxhighlighter" class="brush: js"><![CDATA[
   * SyntaxHighlighter
  function foo()
      if (counter <= 10)
      // it works!

print "Hallo"

If you are using Google's Blogger (aka 'blogspot') as I am, you can prepare for syntax highlighting all blog posts via your Design template. Here are the steps:

  1. Click 'Design' at the top of your blogspot page.
  2. Click 'Edit HTML' at the top of that page.
  3. Find the tag which ends the HEAD section, and before the end insert the following:

<link href='' rel='stylesheet' type='text/css'/>
<link href='' rel='stylesheet' type='text/css'/>
<script src='' type='text/javascript'/>
<script src='' type='text/javascript'/>
<script src='' type='text/javascript'/>

<script type='text/javascript'>
  SyntaxHighlighter.config.bloggerMode = true;


Add brushes for everything you might use, or try the new autoload feature of version 3.0. Then, you can use the pre or script/CDATA blocks as I've shown at the top of this page. If you need more help, follow these directions. Good luck!

1 comment:

  1. Another option is:

    That's much simpler, but not as flexible.