blog.humaneguitarist.org

syntax highlighting with WordPress

[Mon, 06 Sep 2010 19:39:15 +0000]
Thankfully, pretty much nobody reads this blog. If they did, they'd have seen a lot of weird changes going on in real-time concerning some XML code in a recent post. Basically, I've been playing around with various WordPress plugins that support syntax highlighting [http://en.wikipedia.org/wiki/Syntax_highlighting], which is a fancy way of color-coding code examples with color-coding specific to various scripting and markup languages like PHP, Python, XML, etc. Anyway, after playing around with several, I was running into the same issue with the indent stripping as talked about here [http://www.travislin.com/2009/05/guide-to-find-a-wordpress-syntax-highlighter-that-works/]. The use of indentation is paramount to making one's code readable and in some languages, like Python, indentation is required. In other words, this is valid Python code: if a == a: print "The 'a' variable is equal to itself!" But this is invalid: if a == a: print "The 'a' variable is equal to itself!" because the print statement is dependent on a condition. Anyway, what was happening was that I'd put code into WordPress, the indentation and highlighting would look good, but if I wanted to edit my post later all the indentation would be lost when I'd reopened the post in the editor (btw: I use Dean's FCKEditor [http://www.deanlee.cn/wordpress/ckeditor-for-wordpress/]). So here's what appears to fix it: * I installed my preferred WordPress syntax highlighter: [DEL: Syntax Highlighter Compress [http://www.phodana.de/wordpress/wp-plugin-syntax-highlighter-compress/] :DEL] Syntax Highlighter Evolved [http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/]. * I wrote my post and pasted my code directly into the Visual Editor. * I then highlighted only the code and from the Visual Editor's "styles" drop-down menu I chose "Computer Code". * I then edited the post in Source mode. + The indentations had now been converted to the proper HTML entity names [http://www.w3schools.com/HTML/html_entities.asp]. * I replaced the tags with
 tags.
  + The opening 
 tag needs a "class" attribute to specify the type of code (i.e. Python, XML, etc.)
  + For example, I'd use this for Python:
  o 
  + and this for XML:
  o 

From then on, everything seems to be OK. That is to say, I can edit my post at a later time with the Source or Visual Editor and all my indentations are intact.

Here's the earlier Python code using the technique just described:
if a == a:
            print "The 'a' variable is equal to itself!"

And that's that ... I hope.

:P