Preserve white-space in Page

I frequently post pages with code examples. However, WordPress strips out whitespace, thus ruining the indentation and formatting of my code. So this:

<pre>
    selector {
       property: value;
       property: value;
    }
</pre>

becomes this:

Read More
selector {property: value;property: value;}

I found the Raw HTML plugin, which fixes linebreaks, but even with Raw HTML, the spaces aren’t preserved, so it looks like this:

selector {
property: value;
property: value;
}

I also have played with the Preserved HTML Editor Markup plugin, but it does not support <pre> or <code> tags, which is exactly where I need it. How can I preserve multiple contiguous spaces?

Edit: Just to clarify, the white space is stripped out by WordPress before it is sent to the browser: viewing the source code reveals that the spaces have been collapsed.

Related posts

Leave a Reply

4 comments

  1. Perhaps you could do remove_filter( 'the_content', 'wp_filter_kses' ); but that would remove the markup from the rest of the post as well, not just the code bits.

    Perhaps you can try removing the filter as described above, then add a filter on 'the_content' with your own function. In that function you could specify exactly which things to translate to markup, and which things to leave in their original form (e.g. everything that is between <pre> tags for example).

  2. You could use a code highlighting plugin, for example http://wordpress.org/extend/plugins/syntaxhighlighter/. They should be able to keep the white space.

    Subsequent white space gets removed by default in HTML (for example: " " two spaces become " " one.

    You should replace spaces with the code &nbsp;, or you can add the code between <pre></pre> tags (indicating preformatted text)

    (I’ve not tested the plugin or associated with)