Showing posts with label Syntax Highlighting. Show all posts
Showing posts with label Syntax Highlighting. Show all posts

Saturday, July 11, 2009

Blogger Syntax Highlighting

How to add syntax highlighting to Blogger with Alex Gorbatchev's open-source SyntaxHighlighter.
  • Log into your blogspot account, select the "Layout" tab, and then click "Edit HTML."

  • Click "Download Full Template" to make a backup of your current template.

  • Make a copy of your template, open it in an editor, and find the </head> closing tag. Before that tag, add the following:
    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
    <!-- add brushes here -->
    <script type='text/javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
    </script>

  • After the comment that says "add brushes here," add the languages you plan to use. For example, I'm using brushes for Javascript, Bash, SQL, XML/HTML, and C++:
    <!-- add brushes here -->
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>
    See the full list of supported syntaxes.

  • Save your modified template, and upload it to Blogger (again, under Layout > Edit HTML).

  • You should now be able to add syntax highlighting to your blog. Wrap your code in a <pre> tag and specify the brush to use in the class attribute. For example, to highlight a block of SQL:

    <pre class="brush:sql">
    SELECT *
    FROM users
    WHERE user_id = 1212;
    </pre>

    Here's how that looks when rendered:

    SELECT *
    FROM users
    WHERE user_id = 1212;

  • The code you're formatting should be HTML encoded first. Also note that the Blogger preview won't show the formatting; you'll need to either go ahead and publish it or post it to a test blog first.

Syntax Highlighting with JS and CSS

The code syntax highlighting in this blog is being done with SyntaxHighlighter by Alex Gorbatchev. See the instructions on configuring syntax highlighting with Blogger.