Saturday, January 29, 2011

Code Highlighting

Highlighted code in my samples

I found excellent javascript project. It was written by Alex Gorbatchev, and it is free (Thanks Alex!). I will use it to highlight code samples. There is no need to host JS and CSS inside your blog system, you can just reference files instead.
The most popular programming languages are supported here

You can download project and use it in your web sites or you can use hosted version of highlighter. Unfortunately, Google blog system doesn't allow you to insert link tag, but I have used loadjscssfile function to load script and css files.
Lets test hosted version: (javascript example) Here is a function that loads scripts and css.
function loadjscssfile(filename, filetype)
{
   if (filetype=="js"){
       var fileref=document.createElement('script')
       fileref.setAttribute("type","text/javascript")
       fileref.setAttribute("src", filename)
   } 
   else if (filetype=="css"){
       var fileref=document.createElement("link")
             fileref.setAttribute("rel", "stylesheet")
             fileref.setAttribute("type", "text/css") 
             fileref.setAttribute("href", filename)
   } 
   if (typeof fileref!="undefined"){
      document.getElementsByTagName("head")[0].appendChild(fileref)
   }
} 

var pathToScript = "http://alexgorbatchev.com/pub/sh/current/"; 
loadjscssfile(pathToScript + "styles/shCore.css", "css"); 
loadjscssfile(pathToScript + "styles/shThemeDefault.css", "css"); 
loadjscssfile(pathToScript + "scripts/shCore.js", "js"); 
loadjscssfile(pathToScript + "scripts/shBrushJava.js", "js"); 
loadjscssfile(pathToScript + "scripts/shBrushJScript.js","js"); 


Android Java example:
import android.widget.TextView;
public class TestClass {
    private static final int[] LAYOUTS = new int[] {
        R.layout.center,
        R.layout.left, 
        R.layout.right 
    private final Context _context;
    private final ArrayList _data = new ArrayList();
    public TestClass(Context context, ArrayList data){ 
        _context = context;
        _data.addAll( data );
  
    }
}
 

No comments: