Wednesday 9 September, 2009

How to add syntax highlighting to Blogger with Alex Gorbatchev's open-source SyntaxHighlighter.

How to display code (nicely) in Blogger posts
I’ve long been envious of all those blogs that show code, nicely formatted and even with line numbers! I finally found out how it’s done.

How to add syntax highlighting to Blogger with Alex Gorbatchev's open-source SyntaxHighlighter.
1.Log into your blogspot account, select the "Layout" tab, and then click "Edit HTML."
2.Click "Download Full Template" to make a backup of your current template.
3.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>


4.After the comment that says "add brushes here," add the languages you plan to use.
For example, I'm using brushes for Javascript, CSharp, 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/shBrushCSharp.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'/>


5.See the full list of supported syntaxes.

6.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:


SELECT *
FROM users
WHERE user_id = 1212;


6.If Blogger produces an Error message, saying something like a tag isn't allowed, simply click the checkbox to ignore, and hit Publish Post.

7.All thanks goes to Alex Gorbatchev for creating Syntax Highlighter in the first place. If you want to speed up things, you might want to host the Syntax Highlighter files on your own webspace (such as on a free webhost; just google).

8.If you don't care about fancily presented code and just want the job done, visit the HTML Entities Encoder and simply copy-paste...:)

HAPPY CODING :)




1 comment: