Categories
Package/plugin/module WordPress

Plugin: Preserve Code Formatting

This plugin has been updated! Comments to this post are now closed. For the latest download, documentation, and link for posting new comments related to this plugin, visit the plugin’s new homepage at:
coffee2code.com/wp-plugins/preserve-code-formatting
Name:
Preserve Code Formatting
Author:
Scott Reilly
Version:
0.9
Last updated:
29 March 2005
Description:

Preserve formatting for text within <code> and <pre> tags (other tags can be defined as well). Helps to preserve code indentation, multiple spaces, prevents WP’s fancification of text (ie. ensures quotes don’t become curly, etc).

Notes:

Bascially, you can just paste code into <code>, <pre>, and/or other tags you additionally specify and this plugin will:
* prevent all “wptexturization” of text (i.e. single- and double-quotes will not become curly; “--” and “---” will not become en dash and em dash, respectively; “...” will not become a horizontal ellipsis, etc)
* optionally preserve multiple spaces (including indentations) (for the most part, that is; it changes 2+ consecutive “\n” to “\n\n” and “\t” to ” “)

Keep these things in mind:
* ALL embedded HTML tags and HTML entities will be rendered as text to browsers, appearing exactly as you wrote them (including any
).
* By default this plugin filters both ‘the_content’ (post contents), ‘the_excerpt’ (post excerpts), and ‘get_comment_text’.

Example:
A post containing this within <code></code>:


$wpdb->query("
        INSERT INTO $tablepostmeta
        (post_id,meta_key,meta_value)
        VALUES ('$post_id','link','$extended')
");

Would, with this plugin enabled, look in a browser pretty much how it does above, instead of like:

$wpdb->query(”
INSERT INTO $tablepostmeta
(post_id,meta_key,meta_value)
VALUES (‘$post_id’,’link’,’$extended’)
“);
Installation:
  1. Download the file preserve-code-formatting.zip and unzip it into your /wp-content/plugins/ directory.
    -OR-
    Copy and paste the the code ( preserve-code-formatting.phps ) into a file called preserve-code-formatting.php, and put that file into your /wp-content/plugins/ directory. Please ensure you do not introduce any spaces or other characters before the <?php or after the ?>
  2. Optional: There are two settings in preserve-code-formatting.php file that you can customize:
    a. in the function c2c_preserve_code_formatting(), if you want other HTML (in addition to ‘code’ and ‘pre’) to be processed by this function, add them to the $tags array:
    $tags = array('code', 'pre');
    b. in the function c2c_prep_code(), if you do NOT wish for this plugin to help preserve spacing/indentation in the ‘code’/’pre’/etc tags, then set $use_nbsp_for_spaces to be ‘false’. If you decide to do this, you can still preserve code formatting via CSS. Here’s a snippet of what I use:
        
        code, pre {
      white-space: pre;
        }
    
  3. Activate the plugin from your WordPress admin ‘Plugins’ page.
Functions:

function c2c_preserve_code_formatting( $text )

  • $text : Text to be scanned for <code> and <pre> tags

function c2c_anti_wptexturize( $text )

  • $text : Text to be processed in such a way as to prevent wptexturize from doing its thing
Tips & Examples:

N/A

Release Log:
  • 29 Mar 2005 : v0.9 — Released to the public
Copyright & Disclaimer:

Copyright (c) 2004-2005 by Scott Reilly (aka coffee2code)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Acknowledgements:
N/A

76 replies on “Plugin: Preserve Code Formatting”

This dosen’t seem to work well with Textile. Please email me and let me know if you create a new version or the like

Scott – thanks for the plugin. It’s very useful!

A couple of things I noticed:

It doesn’t seem to interact properly with the Markdown plugin – in particular, asterisk and underscore (for emphasis) are still interpreted inside the code tags.
It doesn’t prevent WordPress’ “correct invalidly nested XHTML automatically” feature. For example, if there is an open XHTML tag inside the code tag, WordPress will still add the closing tag, which will be displayed inside the code tag.

Excellent stuff, thank you. The only thing that buggers me is that you still can’t post <?php code ?> between <code> and &lt:/code>, WP strips everything before the comment is stored in the db …

Actually, with a little help from MCincubus on #wordpress who pointed me to the hook I couldn’t find, I think I have the solution. Instead of add_filter('comment_text','c2c_preserve_code_formatting')
I have added this :


add_action('preprocess_comment', 'c2c_ozh_precomment');

function c2c_ozh_precomment ($input) {
  $input['comment_content'] = c2c_preserve_code_formatting($input['comment_content']);
  return $input;
}

This way, everything between code or pre tags get c2c_preserved *before* WP makes its own selection.

Anothing improvement suggestion:

would it be possible to add line numbers? that feature would be awsome 🙂

WordPress Plugin for Code Formatting

I like to post code periodically in my blog entries, but I haven’t found a satisfactory way to do it until now. If you use “code” tags, you wind up killing your indentation. I’ve been using “pre” tags, but they&#8…

[…] As a side note, the code I posted above was helpfully massaged by the Preserve Code Formatting plugin, which was suggested here. It seems to work fairly well, although I might look into making it all look a bit better (possibly with the assistance of a PHP function like highlight_string() or another WordPress plugin—suggestions appreciated). Comment on this entry. Use Textile to format your posts. […]

Decided to have a look at this to fix some pages that have code on them in a dev site that I’m working on… not only does it stop WP from doing curly quotes, it also stops it from rendering any HTML tags inside the pre or code block!

So I can no longer have all my span tags for code colouring – which is a real pity. Any way to let it parse for tags, but single out the curly quotes only?

[…] This new one is just basically an improved version of a plugin by Scott Reilly. There’s just some tweaks to his code to make it work better in my opinion. I’ve also made it so that commenters can use non-allowed HTML tags within their <code> tags in comments. This is done by cloning the default comment processor (wp-comments-post.php) and replacing it with a slightly modified version that processes <code> contents before it’s stripped and inserted into the database. […]

[…] I discovered a useful WordPress plugin, Preserve Code Formatting today. Put simply it allows you to display code in posts without WordPress playing with the formatting (removing indentation, flattening multiple spaces, etc.). It seems to work quite well so should be something I’ll use a lot in the future. It’s also simple to use once installed, you just wrap your code in and tags as you would in standard HTML and the plug-in takes care of the rest. Aren’t people on the Internet nice? […]

Am currently constructing a blog and wanted to take notes on some code I changed as part of a post. I used your plugin, but it still doesn’t seem to solve the ampersand problem. I was trying to demonstrate how I found a good way to get custom rss feed from google which uses an ampersand in the code. It still gets changed to the ampersandamp;. It doesn’t matter if I use pre or code. I see that the last post here was in August, has anyone come up with a solution since then?

[…] Me ha costado un poco acabar la Entrada, me estaba costando demasiado “incrustar” código tanto HTML como PHP en el post… suele ser habitual y hay muchas formas de solucionarlo, una de ellas y por la que he optado ha sido este magnifico plugin que realmente me ha sorprendido, funciona de maravilla y sin preocuparse por instertar etiquetas de ningún tipo ni nada más. Es el: Preserve Code Formatting de Coffee to Code. Muy pero que muy recomendable (el editor visual de WP no me gusta nada… no lo suelo usar […]

Nice Work!!… this plugin is perfect…, very useful to WP user who don’t have to worry with any technic like tags about the plugin.
Only he need write its post.

Very Thx 😉

Hey Scott, thanks for the plugin. It’s been working well with basic code, BUT it seems to have trouble preserving IE’s conditional comments and comment tags in general.

Any idea’s on how i can make this work with preserving html comments?

Thanks 🙂

[…] This on the other hand requires coding a solution. Luckily someone has done the hard work for us. There is an existing plugin called Preserve Code Formatting that handles this. Basically it looks through the HTML source of a posting and looks for <code> and <pre> blocks. When it finds those blocks it removes all of the extra WordPress formatting and handles escaping HTML entity characters. […]

Comments are closed.