Saturday, January 16, 2010

Source Code Syntax Highlighting for Web Pages

Highlighting code syntax has become a common way to improve the code readability and is used broadly in different programming language editors. There are some approaches how to show highlighted code in a web page.

I would divide all of them into the three categories:
  1. If the web-site is on ASP (Active Server Pages) or PHP (Personal Home Page) host and all the files and the web page generating code are under your control then highlighting can be handled by a PHP or ASP routine. In PHP, for example, there are GeSHi (Generic Syntax Highlighter) and CHIP (Code Highlighting in PHP); Actipro CodeHighlighter is ASP.NET Control.

  2. If there is no total control over the web-site as it is, for instance, with Blogger then JavaScript highlighter can be a solution. There are many JavaScript highlighters available, here are some popular ones:
    They all support pretty long list of languages, easy to install and customize.
    In general scripts should be kept either on a host or directly in the page and the drawback with the approach is that too many scripts can degrade a web-page performance.

  3. The straight forward way is to use a highlighting tool which generates HTML code, so the code can be copied and pasted directly in a web-page. There are some online tools of this kind, for example:

    Another possibility is to use offline converters:
    • Notepad++ and SciTE are editors both based on SCIntilla, highlight syntax of many languages and have an option to export the highlighted code as HTML.

    • Pygments is a generic syntax highlighter and it can be used by many different ways including as a standing along converter.

    The direct HTML highlighting approach, for example, seems to be the best suitable for this blog since not so many posts are going to have any code to highlight. Here is a small Python example:
    import Tkinter as tk

    def keycodess(event):
    if event.keysym == 'Escape':
    root.destroy()
    x = event.char
    if x == "a":
    print "A done"
    elif x == "b":
    print "B done"
    elif x == "c":
    print "C done"
    elif x == "d":
    print "D done"
    else:
    print x

    root = tk.Tk()
    print "a. Menu choice A"
    print "b. Menu choice B"
    print "c. Menu choice C"
    print "d. Menu choice D"
    root.bind_all('', keycodess)
    # hiding the tk window
    root.withdraw()
    root.mainloop()

Keep in mind that copying formatted code from Internet Explorer can be an issue - Formatted Code - Internet Explorer's Copy Issue.

0 comments:

Post a Comment