Java source highlighting

Here is a simple practical solution for highlighting source code served from an Apache web server. The motivation behind this was when I wondered how to allow syntax highlight for my SVN hosted source code when viwed with a browser. I came across a very useful tool written in python, pygmentize. Once this python module downloaded and installed, the following settings should be put in Apache httpd.conf file:

Action highlight /cgi-bin/highlight.py
AddHandler highlight .java

the highlight.py is a python script using pygmentise, and here’s the simplicity :


#!/bin/python
import cgi
import cgitb; cgitb.enable()
import os
from pygments import highlight
from pygments.lexers import JavaLexer
from pygments.formatters import HtmlFormatter

def main():
   print "Content-type: text/html\n"
   print highlight(open(os.environ['PATH_TRANSLATED']).read(), JavaLexer(), HtmlFormatter(full=True))

main()

Obviously, this will hilight java or whatever source code, but will not touch files served via WebDAV/SVN (Hopefully!)

Leave a comment

You must be logged in to post a comment.