Thursday, June 16, 2011

Best way to embed source code in Blog


I have came across to many ways in embedding source code in Blogger but found the best one as Vim. The best way is to write open your source code in Gvim and from the "Syntax" choose "Convert to HTML". gVim creates the file .html file with the same name, for example like if you are using "abc.py" it will create "abc.py.html". Following are the steps to use its code:

  1. The file generated would have code like given below you need to copy the text between the style tags an remove the body tag as it may distort your blog's main formatting. (although I have used "Consolas" it is by default "monospace") :
  2. <style type="text/css">
    <!--
    pre { font-family: consolas; color: #000000; background-color: #ffffff; }
    .Constant { color: #ff00ff; }
    .Identifier { color: #008080; }
    .Statement { color: #804040; font-weight: bold; }
    -->
    </style> 
     
  3. Use <pre> </pre> tags to write the code in HTML editing mode for the blog just copy the converted code in between of it and the good thing is that gVim produces HTML escaped characters. Example of a python program has been given below for binary search.
  4. def search(sequence, number, lower=0, upper=None):
            if upper is None: upper = len(sequence)-1
            if lower == upper:
                    assert number == sequence[upper]
                    return upper+1
            else:
                    middle = (lower + upper) // 2
                    if number > sequence[middle]:
                            return search(sequence, number, middle+1, upper)
                    else:
                            return search(sequence, number, lower, middle) 
Other ways includes the use of Javascript Library (Syntax Highlighter Code Project) its client side scripting and support languages like C++, C#, CSS, Delphi, Pascal, Java, Javascript, PHP, Python, Ruby, SQL, Visual Basic, HTML, XML etc. Major issues in using this are adding .js and .css files and also making changes in master template and right angle characters must be HTML escaped, if you are a blogging novice, I advice not to use it.

Some other uses methods include external code hosting projects like Pastie, Snipplr etc in which my personal favorite is pastie.org but it also have some issues of size and code syntax. see the code snippet below.



As you can see the code in the 2nd line if haven't taken to the 3rd one it by passes the boundary and goes out of frame, so its also not well suited for this purpose. It comes with an advantage that it allows conversion into plain text and direct download of the code.
Post a Comment