first post that has color

I think it was about time to add some color to this blog. So, I wrote a little script that will add color to a python script. All you have to do is supply it with a python source file, and it will output the code. I’ve based the lexing on the pygments lexer. Maybe if time allows me, I’ll write a script with support for more source files. I would have used the output from pygments directly, but pygments uses CSS for styling, and I don’t know if I could add the CSS files here, or how could I use inline styling.

### wordpress syntax colouring

import pygments.lexers
import sys
import pdb
from pygments.token import *

def format_comment(comment):
	return "%s" % comment

def format_namespace(namespace):
	return "%s" % namespace

def format_name_namespace(strx):
	return "%s" % strx

def format_keyword(strx):
	return "%s" % strx

def default_handle(strx):
	return strx

	source_file = sys.argv[1]
	sys.exit("you must supply a source file")

python_lexer = pygments.lexers.get_lexer_by_name("python")
contents = open(source_file).read()

func_dict = {
	Token.Comment : format_comment,
	Token.Keyword.Namespace : format_namespace,
	Token.Name.Namespace : format_name_namespace,
	Token.Keyword : format_keyword,

formatted = ""

for token,val in python_lexer.get_tokens(contents):
	func = func_dict.get(token,default_handle)
	formatted += func(val)

print formatted


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog Stats

  • 239,004 hits

%d bloggers like this: