Saturday, 13 January 2007

Syntax Highlighting in Blogger

This is surprisingly hard to do, but I got it cracked. First thing you need is your code converted to HTML - pop over to here (http://www.manoli.net/csharpformat/) for that - Make sure you don't tick "embed stylesheet". You probably don't want to tick line numbers or alternate line background either.

Now grab the css file that they tell you to embed (located here at the min). We now need to embed this into your blog template - so click template (shown below)



Now click edit html and scroll down until you find last style tag before the end head tag

(again shown below!)



Insert the css code here!

Now you are ready to copy that syntax highlighted formatted code into your blog!

Switch to edit html mode in your edit and past your code - its not 100% perfect though, find below some samples of the different options you can pick:

Sample 1: With line numbers + Alternated line background

   1:  using System;

   2:  /// <summary>

   3:  /// Summary description for Class1

   4:  /// </summary>

   5:  public class Class1

   6:  {

   7:      public Class1()

   8:      {

   9:          Console.WriteLine("Hello World");

  10:      }

  11:  }


Sample 2: Line numbers only


   1:  using System;

   2:  /// <summary>

   3:  /// Summary description for Class1

   4:  /// </summary>

   5:  public class Class1

   6:  {

   7:      public Class1()

   8:      {

   9:          Console.WriteLine("Hello World");

  10:      }

  11:  }


Sample 3: Alternate line background only


using System;

/// <summary>

/// Summary description for Class1

/// </summary>

public class Class1

{

    public Class1()

    {

        Console.WriteLine("Hello World");

    }

}


Sample 4: No options selected


using System;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Class1
{
public Class1()
{
Console.WriteLine("Hello World");
}
}
As you can see the other two options for some reason produce the gap between each line. I'm sure looking at the css would help fix that, but Ill leave that for another time!
One final tip - to get rid of the gap it appears to add itself in at the start of the code simply join together the line <pre class="csharpcode"> at the top with the line beneath. Strange but it works! (see below for proof!)
using System;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Class1
{
public Class1()
{
Console.WriteLine("Hello World");
}
}
Hope this has helped!

Ross

2 comments:

Joel De La Torre said...

Thank you very much for you help on this. I was scouring the web on how to do this on my blog.

I also was able to find a workaround for the multiple lines problem.

Once pasting your code into the "Edit HTML tab, go back to the "Compose" Tab and delete the extra lines there. That seems to be the easiest way to fix that.

See my blog at socalsysadmin.blogspot.com

Erik said...

Was looking for a good solution. thanks