Friday, April 10, 2009

Code Syntax Highlight

toolsThe main reason I prefer to use Blogger than WordPress is that Blogger allows me to customize my blog layout with customized scripts and css styles in my blog template. For example, I have some blogs with source codes in C#, JavaScript, HTML, and SQL. It is very easy to include codes in a blog, by using <pre> tag. However, to highlight syntax, you need to sepcify style or to use css class style. Blogger provides this feature for free but you have to pay for this feature at WordPress.

Here are the steps I use to highlight my code syntax:

  1. Add some style to my blog HTML. This can be done through Blogger's Layout|Edit HTML. Check the Expand Widget Tempates to get the whole HTML layout settings and save it as backup before you make any changes.



    Add css classes (defined in { and } area) will be used to highlight code syntax.

  2. Generate HTML codes for my codes. I like to use some web's tools to get the job done. The tool I use is ASP.Net's forum page. I use this forum's post new topic editor to write/past my codes from its Source Code widget. The widget supports several languages which covers my areas. Those snap-shots are examples how I get my codes to HTML.

    1. Click on Source Code widget button




    2. Type in my codes




    3. Click OK to close it.

    4. Click on Edit HTML widget button




    5. Edit or copy the HTML codes



    6. Copy section HTLM codes between <pre ...> and </pre>


    Note: you may notice that ASP.NET's HTML codes contain some css classes. I added those classes to my Blogger's HTML template.

  3. In my blog entry, I paste the HTML codes to my blog. Normally I put the HTML codes between div tags. If the codes are not too long, I use the div with border. If the codes are too long, then I use a div with fixed height so that codes are within a block with scroll bar available to view codes.

    You can see those HTML tags by viewing section of codes (right click a selection of text).


There are many good tools available for syntax highlighting such as Google's syntaxhighlihter, SHJS, HIGHLIGHT.JS, and Highlight. The problem is that most of those tools are for people who have web server. I only have hosted web server like Blogger or WordPress. I cannot put any of my codes and css style files to the server. Blogger provides a way to embed css styles, but I would not want too many css definition codes there. It is just hard for me to maintain.

That's why I like to use ASP.NET's tool to get HTML codes with classes. Another great advantage of ASP.NET's widget is that it will be able to convert some special HTML codes such as > and <.

0 comments: