WP-Syntax Gotcha for Dealing with Less Than and Greater Than Signs

Posted by & filed under , , .

I’ve been digging for a while now into how to fix this annoying issue that I’m having with WP-Syntax plugin when writing code which contains less than (<) or greater than (>) — which, let’s face it, if you have an if / while / for in the code is bound to happen! The trouble is that WordPress automatically escapes these (and a few other characters) when pasting code in the visual editor — and since you need to use the <pre> tag with WP-Syntax, from there on these don’t get interpreted by the browser back as HTML entities and you will left with code “decorated” with &lt; and &gt; — needless to point out that makes code unreadable! This has been annoying me for a while now because it means every time I go back to edit code in a previous article, if the code contains < or > I end up screwing up the whole formatting if I switch (by mistake or not) to the visual editor. (As a side note, I love the visual editor, I prefer using it wherever possible — that’s what it’s there in WordPress for: to make lives easier, right?)

So as it turns out, there is a trick you can use when using the <pre lang="blah"> tag for WP-Syntax / GeSHi and that is by using the escaped="true" attribute in the <pre> tag:

< pre lang="blah" escaped="true">...< /pre >

So let’s look at how this changes the code/behaviour of the output — here’s a sample Java code snippet without the escaped="true". (It might not be obvious due to the mangling of < and > as stated above, but the code is comparing 2 variables and prints out a different message depending which one of the 2 is bigger.)

public void printBigger( int a, int b ) {
 if( a &lt; b ) {
  System.out.println( "b &gt; a" );
 } else if( a &gt; b ) {
  System.out.println( "b &lt; a" );
 } else {
  System.out.println( "b == a" );
 }
}

Looks rubbish doesn’t it?

Now let’s look at how this would look like if we apply the escaped=”true” attribute:

public void printBigger( int a, int b ) {
 if( a < b ) {
  System.out.println( "b > a" );
 } else if( a > b ) {
  System.out.println( "b < a" );
 } else {
  System.out.println( "b == a" );
 }
}

 
Neat huh? 😉

3 Responses to “WP-Syntax Gotcha for Dealing with Less Than and Greater Than Signs”

  1. Liv

    Update to this — it seems the escaped="true" attribute to the <pre> tag gets removed (by whom???) if you switch to the visual editor!
    So unfortunately this only solved some of the problems — make sure when you edit such source code you don’t switch to the visual editor as you will lose this attribute.

  2. Fedek6

    Thanks! Awesome tip 🙂 Saved my life 😀

  3. Neale Blackwood

    Great tip – thanks for sharing.