WordPress Code Highlight Plugin

Post syntax highlighted code, or simply post code that is not affected by the WordPress text replacement features.

Note: This plugin does not work correctly with WP 2.0. I’ve tried to get it to work, but the new WYSIWYG editor is causing a lot of trouble. I’m leaving the download up for anyone who wants to give it a try (re-release if it you wish. I will link to you from this post if you do). I am working on a new plugin that will let you post code, but in a different manner. I am trying to get something together so at least old posts will still display correctly.
You can Download what I’ve done so far and work from that. The problem is something to do with HTML cleanup, I believe. TinyMCE (or a plugin) cleans up invalid code — I’ve tried to fix it by converting HTML into entities, but the cleanup takes place before my TinyMCE plugin can work on it.

» Download: Code Highlight 1.0 Beta 3.1.1 «
On Dec 16, 2005, I released 1.0 Beta 3.1.1 in response to a security issue. It is strongly recommended you upgrade as soon as you can. All you have to do is download the updated archive (linked above), and re-upload the single CodeHighlight.php source file. Thanks to Minkoo Seo for letting me know about this flaw.

Requirements

  • The following PEAR packages are used:
  • Whatever packages are not installed on your system, download them from the PEAR website and place them into the PEAR/ directory included with the plugin. PEAR and XML_Parser are two common packages, so the download here only includes the less common Text_Highlighter package.

Release Notes

  • 1.0 Beta 3.1.1:
    • Fixed security issue that would allow a malicious user to inject SQL into the insert/update queries used for editing/creating new comments/posts.
    • This was the only change from Beta 3.1, no bugs have been addressed in this release.
  • 1.0 Beta 3.1:
    • Added Java to acceptable lang
  • 1.0 Beta 3:
    • Notes:
      • Took out the PEAR base class from the package, now only the Text_Highlighter is included. Since PEAR and the other classes Text_Highlighter relies on are common, I’ve decided to only include the less common Text_Highlighter.
    • Updated Text_Highlighter to newest release (now with Java support)
    • Fixed XHTML validation bugs.
    • Fixed bug with invalid path separator on Mac OSX.
    • Fixed bug when posting one line of code, the code is hidden by padding (now forces a height to one-liners).
  • 1.0 Beta 2:
    • Added filters for comments and excerpts too
    • Added filters for *_pre (Input->database) to combat some issues people might have with the balanceTags function
    • Fixed the issue with slashes being stripped.
  • 1.0 Beta 1: The first release

Note: This plugin is unsupported and does not have any set release schedule. The author (me!) releases it with no guarantees. If lack of support and irregular updates is a problem for you, then you shouldn’t install this plugin. It’s released simply because I like to share my works.

65 Responses to “WordPress Code Highlight Plugin”

  1. Priss Says:

    Hmm…when logged in, the plugin gives an preg_replace() error. But it works just fine when not logged in.

    preg_replace(): Compilation failed: missing terminating ] for character class at offset 34 in CodeHighlight.php on line 66

  2. Priss Says:

    And now works fine since I posted my comment….

  3. Chris Says:

    I was hacking it just as you posted that ;) I didn’t think anyone was going to check it so soon. The download was just updated, btw :) (Changed it from using a pre HTML tag to a BBCode-like [code ] tag.)

  4. Priss Says:

    Hehe. Figures. :P

    So…are you going to enter it in the WP Plugin Competition?

  5. Chris Says:

    I don’t think so. It’s a bit too simple I think, especially considering it uses a premade PEAR class.

    I never knew about that comp though, maybe I’ll think of something else and enter.

  6. ermau Says:

    If the code in your post is supposed to be highlighted… I’m not seeing it.

  7. Chris Says:

    There were additions to the CSS, try doing a refresh to clear your browsers cache.

  8. ermau Says:

    Ah there we go, nice.

  9. swaroop Says:

    It doesn’t work for me. Half the page loads and it looks like the script just dies after that.

    Any way to debug it?

  10. Alex Says:

    Chris: Does this plugin and/or Text_Highlighter have an option for where to place the open-curly-bracket, such as just after the function name vs on the next line? (I prefer the latter, fwiw.)

  11. Chris Says:

    swaroop
    It doesn’t work for me. Half the page loads and it looks like the script just dies after that.

    Any way to debug it?

    What errors are you getting? Note that this plugin has only been tested on PHP4.3.11. I just re-installed it to make sure I didn’t forget something in the package, and it’s working fine for me.

    Alex
    Chris: Does this plugin and/or Text_Highlighter have an option for where to place the open-curly-bracket, such as just after the function name vs on the next line? (I prefer the latter, fwiw.)

    You mean coding style? The Text_Highlighter class doesn’t care:
    [code lang="php"]< ?php
    function myfunc($arg) {
    echo $arg;
    return substr($arg, 5);
    }

    // Or

    function myfunc($arg)
    {
    echo $arg;
    return substr($arg, 5);
    }
    ?>[/code]

  12. Swaroop Says:

    Chris: That’s the trouble, no errors show up. The script just dies.
    I’m running on PHP 5, maybe that makes a difference?

  13. Chris Says:

    I just tried it on my PHP5 install, and it worked fine there too. Very weird.

    Does the script die on every page load? Or just when posting code? Does it still die when the plugin is deactivated?

  14. nick89 Says:

    Looks good chris :)

  15. Rhett Sutphin Says:

    Chris: That’s the trouble, no errors show up. The script just dies.
    I’m running on PHP 5, maybe that makes a difference?

    I had this problem, too. I am also running on PHP5, but that’s not the issue. My problem was that I am running on Mac OS X — specifically, the problem is this block of code:

    [code lang="php"]
    if(strpos(strtoupper(PHP_OS), “WIN”) !== false)
    define(”INI_PATH_SEPARATOR”, “;”);
    else
    define(”INI_PATH_SEPARATOR”, “:”);
    [/code]

    On PHP on OS X, PHP_OS === 'Darwin'. Since OS X uses Unix-style path separators, this block picks the wrong separator.

    You actually don’t need this block at all — just use the PATH_SEPARATOR constant.

  16. Rhett Sutphin Says:

    Ref for PATH_SEPARATOR constant.

  17. Chris Says:

    Ah, right you are Rhett, I did not see that nor did I recall that predefined constant (I knew there must’ve be a more elegant way of doing it!). The fix will be applied in the next posted version.

  18. FuRiOuS1 Says:

    Is there any way to make it so that you don’t need the

  19. Chris Says:

    Need the…?

  20. stefan Says:

    I like your Code Highlight Plugin and will use it in my site I’m currently building. I notice that the XHTML code produced by your plugin is not valid. Maybe you want to correct it in a future version.

    [code]

    [/code]
    should be
    [code]
    
    [/code]
    
    and
    
    [code]

    [/code]
    should be
    [code][/code]

    The CSS is not valid, too. -moz-border-radius is nice but not supported. Also some colors: Orange is #ffa500; Darkred is #8b0000; and Darkblue is #00008b.

    Thanks again for this cool plugin.

    BTW, a new version of Text_Highlighter is available. With “java” support.

  21. fluge Says:

    Please remove the bad shown codes above. Here I’ll try it again:

    /*
    [code lang="xml"]
    Mit dem Fahrrad von Starnberg im Uhrzeiger-Sinn um den See nach Starnberg.

    Unfallstelle König Ludwigs II. bei Perg

    [/code]

    [code lang="php"]
    function popUp($strURL,$strType,$strHeight,$strWidth)
    {
    $strOptions=”";
    if ($strType==”console”) {$strOptions=”resizable,height=”+$strHeight+”,width=”+$strWidth;}
    if ($strType==”fixed”) {$strOptions=”status,height=”+$strHeight+”,width=”+$strWidth;}
    if ($strType==”elastic”) {$strOptions=”toolbar,menubar,scrollbars,resizable,location,height=”+$strHeight+”,width=”+$strWidth;
    window.open($strURL, ‘newWin’, $strOptions);}
    }
    [/code]

    [code lang="xml"]

    [/code]
    */

  22. fluge Says:

    I give it up now. I don’t know how to write the code symbols in this comment sheet.

    Can anyone send me an eMail showing code example, eventually php and html in 1 script?

    Thank you.

    E.G.Fluge
    schneemann_2000@t-online.de

  23. Chris Says:

    @fludge: You are doing it correctly. The PHP highlighting is not showing up because the highlighter requires the <php … ?> tags. The last example is a bug, the h-scroller causes the text to be hidden.

    @stefan: Yes, I know about the non-validation. I will be fixing this (and the other bugs) today (I am going to leave the -moz-x style’s, however). And thanks for letting me know about the new Text_Highlighter — that will be included with the next release as well.

  24. fluge Says:

    Hello!

    Thx for your reply. I think I was misunderstanding the purpose of Code Highlight. I tried to use it for Wordpress postings containing HTML and/or PHP and/or Java Script …..

    I believe I can’t understand its purpose.

    E.G. Fluge

  25. Chris Says:

    No problem fluge. The plugin is to add highlighting so you can show source code in your posts, it is not used to actually execute any code.

  26. stefan Says:

    Thanks for bugfixing, Chris. Just one note: You forgot to at ‘java’ to the $acceptable_lang variable.

  27. jxue Says:

    Hi, I’m testing it out and finding it working great in general - except the missing ‘java’ flag as stefan mentioned. (and it still says “beta 2″ in the plug in info…) Thanks for the nice work done!.

  28. jxue Says:

    Oh, another suggestion - it seems that if the value specified in ‘lang’ isn’t in $acceptable_lang (as in my case before I added ‘java’ to it myself), the plugin would strip off the lang attribute. Is it possible to keep it as is and simply ignore it if it’s not supported? It would leave the door open for us to specify a language even though it is currently not supported by the highlighter.

  29. Chris Says:

    Thanks stefan, slipped my mind :)

    jxue: Thanks for the comments. I will sort that bit about stripping lang off when I’ve got some time to work on it. For now, I’ve made the small edit that adds Java to $acceptable_lang and changed the version in plugin info.

  30. sloecoach Says:

    Can you tell me what the logic is behind how long the block of code can be before it puts a scrollbar in? I have some that are 5 lines some 6, some more. and then a scrollbar hiding 1 line.

  31. who_meee Says:

    Hi,

    I tried your plugin today and encountered the following error whenever I include the ‘lang’ attribute in [CODE] -

    Warning: Wrong parameter count for preg_match() in /home/vijavin/verbage.net/htdocs/wp-content/plugins/CodeHighlight/PEAR/Text/Highlighter.php

    Any ideas?

  32. who_meee Says:

    Okay. Figured that one out. My PHP version is 4.3.2 and the version preg_match assumes in the above call is 4.3.3 - the last offset parameter is invalid in my version.

    I understand that this is PEAR code, but is there any chance you would know how to make the plugin work with the older preg_match?

  33. Chris Says:

    Can you tell me what the logic is behind how long the block of code can be before it puts a scrollbar in?

    If code block is equal to or greater than X lines, apply a fixed height style to generate a vertical scrollbar.

    I understand that this is PEAR code, but is there any chance you would know how to make the plugin work with the older preg_match?

    I don’t think so. You will have to dive into the package code (which I would expect to update regularly, especially since it’s in beta). The easiest way I think would be to make a custom function that creates a substring of $str from position $offset, and then uses the substring with the preg_match function, returning it’s value and assigning it’s matches. Then replace the call to preg_replace where the last parameter offset is used (only two that I can see) with your function instead.

  34. MySchizoBuddy Says:

    Not working for me at all. no colorcoding or scrollbars. I’m using PHP 5.0.4 on MAC OSX, WP 1.5.1.2

    I have pear and xml parser and text highighter installed, but didn’t work, So i copied it inside the Pear directory inside codehighlight, doesn’t work either.

    Here are the versions
    PEAR 1.4.0a12 alpha
    XML_Parser 1.2.6 stable
    Text_Highlighter 0.6.5 beta

    which versions are you using.

  35. Chris Says:

    The colouring/scrollbars is achieved with CSS. Be sure you have placed the CSS code into your main CSS file, and then do a hard refresh (CTRL+F5) to ensure your browser is not viewing a cached copy.

  36. MySchizoBuddy Says:

    can u clarify a bit more. u want the content of addcss.css to be added to wp-admin.css. thats the only CSS file in WP directory

  37. MySchizoBuddy Says:

    plus does it support XML or not. do u have a list of languages that it can support

  38. Chris Says:

    can u clarify a bit more. u want the content of addcss.css to be added to wp-admin.css. thats the only CSS file in WP directory

    No, the CSS should be added to your theme’s CSS file (wp-content/themes/yourtheme/style.css). Sorry, the instructions don’t clarify that very well.

    plus does it support XML or not. do u have a list of languages that it can support

    Yes, xml is supported. The list of languages is posted below the examples in my post above.

  39. MySchizoBuddy Says:

    OK Its working YAY!!.
    Now for some more questions. the $lines variable is for V-scrollbars and not H-scrollbars as the comment states. right?

    I have 31 line of code, yet putting 35 in the $lines doesn’t get rid of the V-scrollbars. not even adding 50 gets rid of em.

    how do i change the tab size?
    how do i change the width of the box?
    Does it have line number option.

    Sorry for so many question. But i love this plugin, this is the only one for WP that actually worked for me. :)

  40. Chris Says:

    Yes, $lines is for the v-scrollers (I’ll have to fix that comment!). I don’t know why it is still showing a vertical scrollbar if $lines is 35, yet you only have 31 lines of code. Lines are counted explicitly and compared against $lines before any force-height styling is produced. Note that even blank lines still count as lines.

    Tab size: I believe you can customize tab size, though it is not an option with this plugin. If you’d like, you can look through Text_Highlighter and see if you can find a way.

    Line numbers: This is possible with the Text_Highlighter package, but again, not an option with this plugin.

    I will add those two options to the next release.

    As for box width, that is defined in the CSS (class hl-surround).

  41. MySchizoBuddy Says:

    thanks for all the help. :)
    ok its firefox problem the scrollbar doesn’t appear on safari browser. I think when ur calculating the box size add a couple of additional pixels to it, so that it works under firefox.

    one last question (promise),it ins’t directly related to ur plugin.
    How can u protect the code from WYSIWYG (like Xinha and tinyMCE). since the code is wrapped around a [code lang][/code], is there a way i can protect it from being altered. My code is Xml and WYSIWYG also seems to parse it, no matter what i do

  42. KosherJava Says:

    Currently you have to update the theme’s CSS file. There is a way to add CSS to the headers on the fly. This is described in the http://asymptomatic.net/wp/2005/02/22/1328/how-to-write-a-simple-wordpress-plugin/ tutorial. The part about CSS can be found on the 5th page of the tutorial.

  43. KosherJava Says:

    You can see an other sample in the Search Hilite plugin at http://dev.wp-plugins.org/file/google-highlight/trunk/google-hilite.php

  44. stefan Says:

    I am experiencing a problem if using the plugin in comments. Instead of the code something like “::HLIGHT_BLOCK_1::” is displayed. This happens since I updated to WP 1.5.1.3 (on two different systems). In posts the plugin works fine. Any idea what is wrong?

  45. Chris Says:

    ::HLIGHT_BLOCK_1::

    Hmm, you’re right. Thanks for bringing it to my attention, I will look into this tomorrow.

  46. Chris Says:

    Test
    [code lang="xml"]test[/code]
    Test

    Okay, so some work and some don’t…

  47. jason Says:

    It would be nice if HTML in PHP scripts was highlighted too.

    e.g.

    ::HLIGHT_BLOCK_1::

    Cheers.

  48. circle Says:

    Very nice plugin! Especially for programming geek like us :-p

    But some suggestion here. Maybe you can provide an option to replace the default <code> tag to yours when the user press the button on the editor!

    Looking forward to your new release with more functions! Really well done, man!

  49. krapplack Says:

    I like it!

    I modified the plugin a bit and wanted to share my code.

    1) I inserted word wrap for the code so that long lines would be cut at 78:

    ## insert at line 139 in CodeHighlight.php

    $wwTxt = split(”\n”,$txt);

    $txt = ”;
    foreach ($wwTxt as $line) {
    $txt .= wordwrap($line, 78, “\n “) . “\n”;
    }

    unset($wwTxt);

    ##

    2) I made the CSS relative to the used font:

    ##

    .hl-surround {
    -moz-border-radius: 0.5em;
    background-color: #F9FBFC;
    border: 1px solid #C3CED9;
    padding: 1em;
    margin-bottom: 1em;
    overflow: auto;
    text-align: left;
    }

    ##

    Cheers,
    Thomas

  50. kem Says:

    Hi.
    It is very wonderful plug-in.
    However, I will look at the following errors, if ‘ is contained in a code.

    ————
    WordPress database error: [You have an error in your SQL syntax; check the-manual-that-corresponds to-your-MySQL-server version-for-the-right syntax to use near '[/code] ‘, post_excerpt = ”, post_title = ”, post_status = ‘publi’ at line 3]UPDATE wp_posts SET post_content = ‘::HLIGHT_BLOCK_1:: ‘and post_excerpt =”, post_title =” and post_status = ‘publish’ and comment_status = ‘open’ and ping_status = ‘open’ and post_author = ‘1′ and post_password = ”and post_name =’20′, to_ping =” and post_modified = ‘ — 2005 - 08 - 20 — 20:31:50 — ‘ — post_modified_gmt — = — ‘ — 2005 - 08 - 20 — 11:31:50 — ‘ — menu_order — = — ‘0′ and post_parent =’0 — ‘ — WHERE ID = 20 Warning: Cannot modify header information - headers already sent by (output started at /srv/www/htdocs/wp-includes/wp-db.php:97) in /srv/www/htdocs/wp-admin/post.php on line 397
    ————-

  51. DreamDreams Says:

    Using 1.0 Beta 3.1 but get no color here. My configuration:
    php 5.0.4
    PEAR 1.3.6
    XML_Parser 1.2.4
    And I did copy the content of add_css.css to my themes css.
    Actually it’s not ‘no color’. It’s all default color. If I view the HTML source from my browser, I only see hl-default and hl-main, no other classes. And I got no errer, like missing PEAR/Parser functions etc, when loading the page.
    Does anybody have similar experience?

  52. DreamDreams Says:

    Sorry for the last comment. My bad. Actually I enclosed a slice of php code without so that the parser doesn’t recognize it. But this plugin can recognize it. :(

  53. Ivan Georgiev Says:

    When I tried to activate the plugin it failed to run, because it was unable to find the PEAR.php file. Please include it along with the distribution for the people without PEAR.

  54. laurenceo Says:

    Chris, thanks so much for your great tool!

    I created a simple quicktag to make inserting the code lang=”" tags easier. I hope it will be beneficial to the users of your plugin.

  55. mcquayb Says:

    kem: I receive a very similar error. Did you ever get this working?

  56. Treedent Says:

    On my local installation the plugin works fine with all the PEAR packages descibe at the top of this page, but I use a shared server for my online web blog and some php function have been disabled for obscur security reasons such as the ini_set function.
    This function is used to add the PEAR path to the php include_path, in the “CodeHighlight.php” file :

    ::HLIGHT_BLOCK_1::

    So the activation of the “code hilight” plugin generates error.

    To correct the problem, I try to specify the real path of the PEAR folder, everywhere it’s needed :

    - in CodeHighlight.php
    - in Highlighter.php

    And the activation of the plugin works fine.

    The problem now is that the “highligth” function generate an error like “Call to undefined function: highlight()” in the “CodeHighlight.php” file at line 145 :

    ::HLIGHT_BLOCK_2::

    How could I do to make the highlight function visible ?

  57. Robert Smallshire Says:

    Regarding the problem with unnecessary vertical scroll bars in with code that shouldn’t be long enough to trigger the vertical scroll. This seems to be triggered by lines of code which are sufficiently long to trigger the horizontal scroll bar. When the horizontal scroll bar is triggered, the vertical scroll bar it triggered too.

    The workaround it to avoid having long lines of code that trigger the horizontal scrollbar.

    Hope this helps somebody. I’m no CSS expert but is there don’t seem to be separate vertical/horizontal settings for the overflow attribute in h1-surround.

    Hope this helps somebody!

  58. minkoo.seo Says:

    Hello Chris. My name is Minkoo Seo, and I’ve found some important security problem. Could you email me? I can’t find your email address, so I’m writing to you using comment.

  59. minkoo.seo Says:

    Ah, I forgot to mention that the problem is related to CodeHighlight which I love very much.

  60. Arno Simon Says:

    Hello Chris,

    I just installed your tool on my website. Unlikly it seems not to work.

    I added a
    [code lang="php"][/code]
    to an static page. The frame and the code appears… even there’s nothing highlighted. Insted of ‘

  61. Arno Simon Says:

    ups.. Sorry…. at “I added a” I entered a code-tag with >?php echo “some php code”& ?<..

    Just the code disappears on your site, too.

    After “Instead” (sorry for misspelling…) I wrote: Instead of highlightning the source a blank appears between > and ? so your parser will not longer detect propper php-code, I asume. Is that correct?

    What do you think, which other plugin will fire in front of yours?

    reg.

    Arno

  62. sn0n Says:

    I’m having a problem with escape characters (the backslash n) and what not, any way to fix that? love the plugin otherwise, its just makin me adapt my code to a plugin. know what i mean? get back to me.. thnx!!! :-D

    love the plugin btw..

  63. sn0n Says:

    and of course the second i open my mouth, it works.. :: inserts foot ::

  64. Arno Simon Says:

    Well…. That’s what I understand by supporting your own tools! Great work, Chris! I think the next place your tool will see at my PC ist the Trashcan.

    regards

    Arno

  65. Chris Says:

    Arno: I just tried that PHP code here and it works fine. Code in comments is buggy (as you could have figured from reading previous commenters). I will fix bugs when I have spare time, which is little, especially at this time of year. Note to anyone: this plugin is GPL’ed. Anyone can take what I have done and add features/bug fixes to it as they wish. It’s a relatively small plugin, the bulk of the functionality resides in the PEAR packages.

    The plugin is released simply because some people might find it useful. You must understand that, as pointed out in the blog post, the plugin is unsupported and does not follow a release schedule. If it does not work for you or you have a problem with these “terms”, then obviously this is not something you should use.

    I’m sorry I don’t have unlimited time to support and update things that I have unconditionally released for public use. I have a life, a job and things of greater importance. If you think my time and efforts, which I give away freely without asking for anything in return, belong in your trashcan: so be it. But I do ask a simple favor: do not come to my site and mock me.