Dean Lee’s Source Code Syntax Highlighting Plugin
Sep 6th, 2007 by jon
If you are a fellow technologist then you will most likely want to place code examples in your blog posts at some point. This can become a difficult and frustrating process because many common characters found in source code will not show up on an HTML page. One solution would be to link to the source code file itself and allow users to download it, but this can be annoying to the user (epically if you are showing them a hello world application). Another common solution would be to write a CSS class for <pre> and <code> but you will not have automatic syntax highlighting.
After starting work on ThinkProgramming (now CrankyCoders.com) I began my search for a module which would allow easy syntax highlighting within posts. What I found was Dean Lee’s Source Code Syntax Highlighting Plugin for Wordpress which is built on GeSHi. The Syntax Highlighting Plugin overloads the <pre> tag and it allows you to specify which language you want to use, such as <pre lang=”python”> or <pre lang=”php”>. For example here is some simple code in a few different languages.
C/C++
-
#include <stdio.h>
-
-
int checkpass(void); // function prototype
-
int main (void)
-
{
-
int x;
-
x = checkpass(); // calls function
-
fprintf(stderr, "x = %d/n", x); // print the value of x
-
if (x) // if x is not zero then
-
fprintf(stderr, "Password is correct!/n");
-
else // x has been returned as a zero
-
fprintf(stderr, "Password is not correct!/n");
-
return 0;
-
}
Python
-
def print_menu():
-
print ‘1. Print Phone Numbers’
-
print ‘2. Add a Phone Number’
-
print ‘3. Remove a Phone Number’
-
print ‘4. Lookup a Phone Number’
-
print ‘5. Quit’
-
print
-
numbers = {}
-
menu_choice = 0
-
print_menu()
-
while menu_choice != 5:
-
menu_choice = input("Type in a number (1-5):")
-
if menu_choice == 1:
-
print "Telephone Numbers:"
-
for x in numbers.keys():
-
print "Name: ",x," \\tNumber: ",numbers[x]
-
print
-
elif menu_choice == 2:
-
print "Add Name and Number"
-
name = raw_input("Name:")
-
phone = raw_input("Number:")
-
numbers[name] = phone
-
elif menu_choice == 3:
-
print "Remove Name and Number"
-
name = raw_input("Name:")
-
if numbers.has_key(name):
-
del numbers[name]
-
else:
-
print name," was not found"
-
elif menu_choice == 4:
-
print "Lookup Number"
-
name = raw_input("Name:")
-
if numbers.has_key(name):
-
print "The number is",numbers[name]
-
else:
-
print name," was not found"
-
elif menu_choice != 5:
-
print_menu()
-
As you can see, the plugin does a great job of making code examples very easy to read. For anyone who includes code in their blog this plugin is an absolute must. Also be sure to checkout Dean Lee’s other plugins such as the Google Code Prettify for Wordpress which is very similar to the Syntax Highlighting plugin except that is uses Javascript to format the code.
If you like this post, then consider buying me a beer!