Just trying out some different methods of doing code display and syntax highlighting with a short snippet of basic Python module code.

 

Basic <code> tag

def main():
    pass

if __name__ == '__main__':
    main()

Well that’s pretty ugly, and I have to use “&nbsp;” to do indenting (pretty important for Python).

 

Wrap with a <pre> tag

A simple improvement is to wrap the <code> tags in <pre> tags. This will preserve formatting (tabs, spaces, newlines, etc.)

def main():
    pass

if __name__ == '__main__':
    main()

That looks much better. I can even copy from the webpage and paste into PyScripter and all the formatting characters come with it.

TIP: Add this line to your CSS to ensure that the code is using a monospace type (for consistent indenting). Most browsers do this by default, but you can force it to make sure.

pre { font-family: monospace; }

 

Google Code’s Prettify

Now, let’s try some syntax highlighting. Google Code’s Prettify is used on Google Code and StackOverflow for their highlighting. It has some nice features (ie, autorecognizes most major languages, also can specify the language, optional line numbering).

Since this is WordPress, “there’s a plugin for that”! The one used below is called “Prettify Code Syntax” by Jesús Carrera.
Just add the “prettyprint” class to the pre tag. Optionally you can add a language specifier class to the code tag as well.

def main():
    pass

if __name__ == '__main__':
    main()

Simple and looks great!

For line numbering, also add the “linenums” class to the <pre>

def main():
    pass

if __name__ == '__main__':
    main()