Skip to content

WordPress and Source Code Posts

March 3, 2007

If you try to use the TinyMCE editor bundled in with WordPress to edit posts you’ll soon realize that posting source code or any other preformatted section to you blog is going to be any thing but pain free!

For developers, Linux and shell enthusiasts posting source code snippets, configurations, or shell commands is an everyday need, and Blogs, should make this easy and effortless, but they don’t!

Like many others I disabled the Visual editor and went back to the dark ages when web development was done on vi and icons were square and had a 16 color pallete…

The problem is that in an effort to “cleanup” the resulting post content WordPress and many others insert, or remove line breaks, replace them with <BR> tags, delete spaces and tabs, etc, etc, rendering all preformatted code into a useless pile of junk.

After digging in WordPress’s insides, I found that the culprit behind all the pain was the WordPress TinyMCE plugin. This is not a WordPress plugin, but a JavaScript TinyMCE plugin that does some WordPress related functions.

One of the things it does is to scan <pre> code sections and replace all new lines with <br> tags. This is ridiculous!!!!!!!!
Why would anyone want to do this? The <pre> HTML section as the name implies is pre-formated it DOES not need your help to format so you should leave it alone.

Well to fix this terrible oversight you should edit the file wp-includes/js/tinymce/plugins/wordpress/editor_plugin.js.

Search for cleanup: and look for the comment that reads (at least in version 2.1.1 it did)

// Look for \n in <pre>, replace with

and comment the whole while loop. Like so

/* var startPos = -1;
while ((startPos = content.indexOf(‘<pre’, var=”” endpos=”content.indexOf(‘<pr>”>’, startPos+1);
var innerPos = content.indexOf(‘>’, startPos+1);
var chunkBefore = content.substring(0, innerPos);
var chunkAfter = content.substring(endPos);

var innards = content.substring(innerPos, endPos);
innards = innards.replace(/\n/g, ‘
content = chunkBefore + innards + chunkAfter;

Save the file and edit your posts with source code without any problems!
Just a word of advice, select the whole section of the post that has the source code snippet and then apply the Pre formatted style to it. If you select the pre formatted and then write the text it will insert a new <pre> HTML tag for every line you type. This is also very annoying. Maybe in another post I’ll take care of that…


From → Wordpress

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: