Formatting Source Code with WordPress

Sometimes you get used to doing things one way and you forget to take a step back now and then and see if there isn't something you're missing. In my case, I was formatting source code on this blog by putting html non-breaking spaces and < codes for angle brackets etc. Ouch. What was I thinking.

Here is a much better way to do it. Use the CodeHighLigher plugin. All you have to do after enabling the plugin, is place your source code in a pre tag. Add the lang attribute to the pre tag and you'll end up with code formatted in a number of languages. The usage section of the plugin document has all the details and languages. I'll not add that again here. Here is an example though:

  1.  
  2. <pre lang="cpp">
  3. #include <iostream>
  4. int main(int argc, char* argv[]) {
  5. cout << "Hello Code Formatter Plugin" << endl;
  6. }
  7. </pre>
  8.  

You can include code that would otherwise be formatted by the plugin by putting a space between the end angle bracket and the forward slash for the pre tag. The plugin then outputs the ending pre tag correctly for formatting.

Here is the above code formatted by the plugin:

  1.  
  2. #include <iostream>
  3. int main(int argc, char* argv[]) {
  4. cout << "Hello Code Formatter Plugin" << endl;
  5. }
  6.  

Again, I'm not sure why I didn't find this sooner.

1 Response to “Formatting Source Code with WordPress”


  1. Maverik

    Nice post..
    Also found a nice eclipse plugin to directly copy code as HTML from eclipse IDE.

    http://java-sample-program.blogspot.com/2012/12/copy-as-html-eclipse-plugin.html



css.php