Code Snippet

First off, Code Snippet 2.0 is not mine. I didn’t make it, I won’t take any credit for it. The original creator was the person who hosted a blog at http://blog.enargi.com/codesnippet/ (which no longer works and is apparently down for good; however, it is GPL.). I came across the plugin awhile ago and and I’ve decided that I couldn’t just let it be lost to the ages and I’ll let it live here as long as I’m able.

Straight from the readme.txt, Code Snippet 2.0 is is a WordPress plugin for displaying code with highlighting in blog posts. The plugin uses GeSHi syntax highlighter engine. I’ve seen others, but they’ve gone the way of the dodo and most of them didn’t have as many supported languages at Code Snippet 2.0. I also think that Code Snippet does a better job than the Code Auto-escape plugin.

Install

  • Download the plugin here.
  • Copy archive to wp-content/plugins directory
  • Extract the zip file
  • When extracted properly you should have following directory structure: /wp-content/plugins/codesnippet
  • Since I’ve not tore through the code, the plugin will probably not work if extracted/copied in diffrenet directory.
  • Enable the Plugin

Usage
The original author recommended always wrapping your code in a <pre> tag; however, I’ve found that you generally don’t need to. To use it, simply surround your code with as such and specify your language type:

[code lang="c"]
int main(int argc, char** argv) { return 0; }
[/code]

And you get this:

int main(int argc, char** argv) { return 0; }

Or you could do something like:

[code lang="php"]
<?php
echo “Hello World!”;
?>
[/code]
<?php
     echo "Hello World!";
?>

If you find a bug in it, drop a comment or an email to wyatt dot neal at gmail and I’ll try my best to fix it for you.

Also, if you have find that your language isn’t here and you write your own GeSHi hack to work with it, let me know and I’ll drop a link on this page so that people can find you. Heck, I’ll even put it in the archive so the world can share it if you want. Here’s the list of supported languages:

Collapse Language List

  • actionscript-french
  • actionscript
  • ada
  • apache
  • applescript
  • asm
  • asp
  • bash
  • caddcl
  • cadlisp
  • c_mac
  • c
  • cpp
  • csharp
  • css-gen
  • css
  • delphi
  • diff
  • div
  • dos
  • d
  • eiffel
  • freebasic
  • gml
  • html4strict
  • ini
  • inno
  • java
  • javascript
  • lisp
  • lua
  • matlab
  • mpasm
  • nsis
  • objc
  • oobas
  • oracle8
  • pascal
  • perl
  • php-brief
  • php
  • python
  • qbasic
  • sdlbasic
  • smarty
  • sql
  • vbnet
  • vb
  • vhdl
  • visualfoxpro
  • xml

Popularity: 20% [?]

Trackback URL.

67 Comments

  1. Jeremy Lavergne says:

    I’ve not looked yet, but does this plugin just use the highlight files from VI or the likes? It would seem that it’d be easily updated then by adding new files from VI or what have you.

  2. Wyatt says:

    I’m not really sure, Jeremy. Looking at the code it appears that it’s really just an assembly of everyone else’s GeSHi PHP translators with some tweaked wrapping to make it work correctly in WordPress. I just can’t remember if VI uses the GeSHi stuff or not.

  3. JR says:

    You should mention adding the codesnippet/codesnippet.css link to the header and defining the codesnip-container class in the installation instructions.

  4. Wyatt says:

    The following has been added to the readme.txt thanks to JR:

    After looking more carefully at the code, I see that it adds the following action to wp_head:

    function addCssStyle() {
         echo ‘<link rel="stylesheet" href="’.get_option(’siteurl’).$this->pluginLocation.‘/codesnippet.css" type="text/css" />’, "\n";
         echo ‘<style type="text/css">’, "\n";
         echo ‘.codesnip-container  {’.$this->getStyle().‘}’, "\n";
         echo ‘</style>’, "\n";
    }

    That automatically adds a link to the provided css file and a separate style for the codesnip container (as defined in the plugin config, I would assume). I don’t use wp_head in my custom theme, so that’s why it didn’t link to it automatically. You might want to include a small note for custom theme users to link to the css and define a style for codesnip-container.

    Details are in the readme.txt. Thanks again JR.

  5. Bladimir Favio Yapura - Blog » Blog Archive » Nuevo PlugIn says:

    [...] PlugIn 0 Comments Acabo de instalar un nuevo plugin para mi blog, se trata de Code Snippet, para que sirve?? para escribir esto por [...]

  6. takn says:

    thanks for keeping this great plugin alive.

  7. Løb og fiks PHP! | Mattias’ virtuelle hukommelse says:

    [...] Bemærk i øvrigt lige det super seje plugin jeg har installeret, der sørger for at farve PHP-koden efter bedste principper Plugin’et kan for de interesserede downloades herfra: http://blog.hackerforhire.org/2007/03/16/code-snippet-20/ [...]

  8. Lustiges Computieren » Blog Archive » Codeschnipsel says:

    [...] verwendet. Leider gibt’s die Seite des Authors nicht mehr, wobei sich dieser nette Herr freundlicherweise der Pflege des auf GPL basierenden Codes angenommen [...]

  9. Eric and Jessica » Blog Archive » Small fixes says:

    [...] and to get those fancy code blocks to show up I installed the Code Snippet 2.0 plug-in and disabled my WYSIWYG editor. We’ll see how that [...]

  10. gad says:

    thx for this wonderful plugin.

  11. The Historical Webber » Blog Archive » How does the yahoo/flash map work… says:

    [...] thanks to CodeSnippet for providing a way to show code. This was the 5th one I tried that finally [...]

  12. Bernie SR says:

    Would this plugin dispaly the code in my posts , I have inadvertently added some code from a widget to my blog. Every time that I post the widget is enbedded in each message. Obviuosly I want to renmove the offending code

  13. Wyatt says:

    Bernie, I don’t think that it would do this; however, I’m not very familiar with the new WP-widget system. This plugin should only display code that you have wrapped in a code block.

  14. John says:

    Great plugin. This saves a lot of time.

    Im having trouble displaying the line numbers. I checked the option and it displays a grey bullet point in front of each line. Any tips?

  15. John says:

    No worries now. It seems that my themes CSS was overiding the list style.

  16. Wyatt says:

    Glad to heard that you got it fixed before I had a chance to look at it John.

  17. In a galaxy far far away… » Blog Archive » Enargi Code Snippet Plugin says:

    [...] was able to download the plugin here after finding the original host was [...]

  18. Lexxy`s Blog » Blog Archive » Code Snippet says:

    [...] hier Code Snippet [...]

  19. The Double Zero » Blog Archive » Codesnippet and firestats incompatability - finale says:

    [...] Go grab the code snippet plugin and if you like codesnippet copy this image, put it on your sidebar and show your appreciation! [...]

  20. מחשבות, מחשבים, ושאר דברי בלע » Blog Archive » CodeSnippet says:

    [...] לי לגלות פלאגינים מעניינים ושימושיים. פלאגין כזה הוא Code-Snippet 2.0, שמאפשר שתילת קוד בפוסטים וצביעה שלהם בהתאם, ממש כמו [...]

  21. seramar says:

    Hey recently I posted a snippet in a post and after a reader tried to paste the code into their blog I found a new problem -

    The codesnippet plugin converts ” ” to curly quotes… and therefore are not always/universally recognized by web browsers or processed correctly.

    To view the specific example: http://www.thedoublezero.org/comment-exchange-movement

    When a reader tried pasting it into their sidebar it wouldn’t work. I asked about their theme and tried it out and found the problem to be the quotes. Any idea on how to override this OR to fix it permanantly?

    Thanks, man - so far your responsiveness has been great!

    Seramar

  22. seramar says:

    found the fix… it appears that the offense is contained to lang=”html4strict”

    To fix it go to the html4strict.php file contained in wp-content/plugins/codesnippet/lib/geshi/html3strict.php

    Line 57 will read:

    ‘QUOTEMARKS’ =&gt; array("’", ‘"’),

    Delete everything between the parenthesis so it looks like

    ‘QUOTEMARKS’ =&gt; array(),

    Should fix your issues.

    Thanks anyway - glad if I was of any help!

  23. seramar says:

    bah! That is kinda messed up… codesnippet didn’t work right, but anyway you should get the idea. I will also submit the fix to the GeSHi folks and hope they take care of it.

    -Seramar

  24. Wyatt says:

    Alright everyone, I’ve tagged out a 2.1 version of CodeSnippet, which is the download link on this page. I’m going to be upgrading the GeSHi to the latest and greatest as well as adding in some new functionality.

    This is going to be living at http://blog.hackerforhire.org/code-snippet/ from now on and I’m probably not going to be monitoring this post :-)

    Thanks for all the feedback!

  25. Wyatt says:

    I’m testing out the newest version to see how the new languages will work. Looks good to me :-)

    Ruby test

    # The Greeter class
    class Greeter
    def initialize(name)
    @name = name.capitalize
    end

    def salute
    puts "Hello #{@name}!"
    end
    end

    # Create a new object
    g = Greeter.new("world")

    # Output "Hello World!"
    g.salute

  26. Jason says:

    function addCssStyle() {
         echo ‘pluginLocation.‘/codesnippet.css" type="text/css" /&gt;’, “\n“;
         echo ‘’, “\n“;
         echo ‘.codesnip-container  {’.$this-&gt;getStyle().‘}’, “\n“;
         echo ‘’, “\n“;
    }
  27. Wyatt says:

    Yeah, sorry Jason. Line numbers and file-reading aren’t in the code yet. I have to find a good way to secure it so someone couldn’t say file=”wp-config.php” lines=”1-20″

    It’s coming, I promise :-)

  28. Sin Ideas » Internet Explorer y max-height says:

    [...] aqui, todo culpa de IE y [sarcasmo]su grandioso soporte de los estándares[/sarcasmo]. Al poner el plugin para resaltar la sintaxis del código que escriba, quize que si el código era muy grande lo [...]

  29. Wyatt says:

    Alright, comments on this post are closed. From now on, use the main-page for this.

    http://blog.hackerforhire.org/code-snippet/

  30. Chronicles of the Hidden Truth » Installing Code Snippet 2.0 plugin says:

    [...] As I expect to be able to publish some articles with source code, I was wondering about the availability of Worpress plugins dealing with syntax highlighting. Fortunately I was not alone on that, and I download this nice plugin CodeSnippet [...]

  31. Mike Saeger says:

    I can’t get this VB code to display properly:

    If Request.QueryString(”mi”) “” Then
    ddmi.SelectedIndex = ddmi.Items.IndexOf(ddmi.Items.FindByValue(mi))
    btnSearchClick() ‘
    End If

    The (less than) and (greater than) signs always show up as < and > instead of the actual symbols.

  32. Mike Saeger says:

    My previous comment is confusing. What I should have said is that the (greater than) sign shows up as (ampersand gt ;) and the (less than ) sign shows up as (ampersand lt;)

  33. Wyatt says:

    If Request.QueryString("mi") <> "" Then
         ddmi.SelectedIndex = ddmi.Items.IndexOf(ddmi.Items.FindByValue(mi))
         btnSearchClick()
    End If

    Looks like it works to me. Remember to wrap your code with the [ code ] block (minus the spaces).

    Now I will admit that if you copy and past this, it’s probably going to give you some weird “quote” signs because of how the GeSHi engine works. If you have a complaint about that, you’ll need to take it up with them :-)

  34. Natrium says:

    I just had the same problem with > and into >
    And the codesnippet-plugin doesn’t seem to recognize the >

    Solution: use the code-editor in stead of the visual-editor of Wordpress.

  35. Natrium says:

    second try :-)

    I just had the same problem with > and into &gt;
    And the codesnippet-plugin doesn’t seem to recognize the &gt;

    Solution: use the code-editor in stead of the visual-editor of Wordpress.

  36. Mike Saeger says:

    I even turned off the Visual Editor in my Profile and as soon as I hit SAVE, or SAVE and Continue the < > signs disappear. It must be in the version of WordpressMU I’m running (wordpress-mu-1.1.1). If I use the Visual Editor then the < > are replaced by their ampersand lt/gt semicolon html names.

  37. Wyatt says:

    Natrium makes a very valid point. I never used the Advanced/Visual editors to write code blocks, generally because they caused more headache than anything.

    Mike, are you sure you are wrapping things in the
    [code lang="vb"][/code] tags? If you aren’t, I know even the raw/standard editor in WordPress will remove <>. I think that it looks like an unclosed tag to WordPress.

    I’ll see what I can do to get &gt and &lt found in the parsing.

  38. Crusty Blog » Blog Archive » Test GeSHi says:

    [...] a couple different syntax highlighters for Wordpress. The one I’ve settled on is CodeSnippet. This plugin allows syntax highlighting by using code blocks. [...]

  39. Pets Information Directory » Eulogy pet says:

    [...] eulogy pet footer sore for you reassurance sturdy couchs. Some of you are within useing what the eulogy pet is intelligent [...]

  40. ctcodre’s blog » Blog Archive » code snippet says:

    [...] tag-ului . ceea ce am gasit astazi este un plugin care face cam aceleasi lucruri. look here for Code Snippet. Si un mic test sa vedem daca merge: [code lang=”java”] public class HelloWorld { [...]

  41. MB.MathemaTeX » Archive du blog » Code Snippet says:

    [...] Site officiel : http://blog.hackerforhire.org/code-snippet/ [...]

  42. MacScripter: Introduction to Database Events at The Joy of Scripting says:

    [...] 27.10.2007: Or just have a look at the library code right here: (Test of the Code Snippet plugin for [...]

  43. Banan says:

    If someone will have trouble with bash language, just download the original geshi.php file form http://qbnz.com/highlighter/ and replace it with the one in the code snippet package. It work’s fine for me :)

  44. Wyatt says:

    Testing update to the GeSHi stuff. This fixes the bash issue referenced above.

    #!/bin/bash

    echo "This is a terrible test example";

    FILE=`which yes`;

    for i in `seq 1 91`; do echo $i | $FILE; done

  45. Rob’s geeky discoveries Blog » Flash getURL clickthrough workaround for MySpace says:

    [...] You’ll have to manually swap those curly brackets for standard double quotes as Code Snippet doesn’t like this [...]

  46. Create Digital Media » phpBB to bbPress Migration Process - Step 1, Remove Spam Users says:

    [...] aside: The lovely code highlighting in this post was provided with the Code Snippet Wordpress plugin, which I installed because WP was misinterpreting my [...]

  47. muttznutz says:

    Hi,
    Excellent plugin, and thanks for keeping it running.
    I think I’ve found a bit of an “undocumented feature”.
    My problem was that putting code into comments didn’t load the .css file.
    I’m not a php wizz, but I think it may be because of the pageHasCode test in codePresentInPosts().
    So if there’s no code in the original post, CodeSnippet won’t detect it in the related comments.
    Nothing I can’t work around, but it would be useful if you could confirm.

    Thanks — Andy

  48. Wyatt says:

    Hi Andy,

    You’re right, CodeSnippet will not highlight code in comments if there isn’t a previous [code] block in the post. I don’t have a quick workaround for this other than putting in a blank [code] block for people that don’t want to touch the code; however, that looks absolutely stupid. I’m not sure what impact pushing everything through the filter; however, I’ll take a look at it.

  49. Wyatt says:

    Rob mentioned he was having an issue with the following block of code. It seems to be a problem with the GeSHi ‘html’ parser. My recommendation is to use the ‘php’ one instead as it seems to catch the flakeyness.

    HTML Version:

    <style type=”text/css”> table.adiflmw { width: 396px; height: 250px; border-width: 0px 0px 0px 0px; border-spacing: 0px; border-style: none none none none; border-color: white white white white; background-color: white; } table.adiflmw td { border-width: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; border-style: none none none none; border-color: white white white white; background-color: white; -moz-border-radius: 0px 0px 0px 0px; } a:link, a:active, a:visited { color:#ffffff; } </style> <table class=”adiflmw”> <tr> <td valign=”top” align=”left”> <span> <a href=”http://adidaswidgets.glueserv.co.uk/v9/” id=”adiCt1″ rel="nofollow"><img src=”http://adidaswidgets.glueserv.co.uk/v9/adiflm396×38.jpg” border = “none” /></a><br /><object type=”application/x-shockwave-flash” allowScriptAccess=”never” allowNetworking=”internal” height=”130 name=” width=”396align=”middle” data=”http://adidaswidgets.glueserv.co.uk/v9/Clock02.swf?spURL=http://www.justgiving.com/gorillarob&getCountDownLink=http://adidaswidgets.glueserv.co.uk/v9/”> <param name=”allowScriptAccess” value=”never” /> <param name=”allowNetworking” value=”internal” /> <param name=”movie” value=”http://adidaswidgets.glueserv.co.uk/v9/Clock02.swf?spURL=http://www.justgiving.com/gorillarob&getCountDownLink=http://adidaswidgets.glueserv.co.uk/v9/” /> <param name=”quality” value=”high” /> <param name=”wmode” value=”opaque” /> <param name=”bgcolorvalue=”#ffffff” /> </object> <br /> <a href=”http://www.justgiving.com/gorillarob” id=”adiCt2″ rel="nofollow"><img src=”http://adidaswidgets.glueserv.co.uk/v9/adiflm396×82.jpg” border = “none” /></a> </span> </td> </tr> </table>

    PHP Version with some cleanups:

    <style type="text/css">
    table.adiflmw { width: 396px; height: 250px; border-width: 0px 0px 0px 0px; border-spacing: 0px; border-style: none none none none; border-color: white white white white; background-color: white; }
    table.adiflmw td { border-width: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; border-style: none none none none; border-color: white white white white; background-color: white; -moz-border-radius: 0px 0px 0px 0px; }
    a:link, a:active, a:visited { color:#ffffff; }
    </style>
    <table class="adiflmw">
    <tr>
    <td valign="top" align="left">
    <span>
    <a href="http://adidaswidgets.glueserv.co.uk/v9/" id="adiCt1" rel="nofollow"><img src="http://adidaswidgets.glueserv.co.uk/v9/adiflm396×38.jpg" border="none" /></a><br />
    <object type="application/x-shockwave-flash" allowScriptAccess="never" allowNetworking="internal" height="130 name=" width="396" align="middle" data="http://adidaswidgets.glueserv.co.uk/v9/Clock02.swf?spURL=http://www.justgiving.com/gorillarob&getCountDownLink=http://adidaswidgets.glueserv.co.uk/v9/">
    <param name="allowScriptAccess" value="never" />
    <param name="allowNetworking" value="internal" />
    <param name="movie" value="http://adidaswidgets.glueserv.co.uk/v9/Clock02.swf?spURL=http://www.justgiving.com/gorillarob&getCountDownLink=http://adidaswidgets.glueserv.co.uk/v9/" />
    <param name="quality" value="high" />
    <param name="wmode" value="opaque" />
    <param name="bgcolor" value="#ffffff" />
    </object>
    <br />
    <a href="http://www.justgiving.com/gorillarob" id="adiCt2" rel="nofollow"><img src="http://adidaswidgets.glueserv.co.uk/v9/adiflm396×82.jpg" border = "none" /></a></span>
    </td>
    </tr>
    </table>

    I think it has to do with the weird characters that are being used … probably a GeSHi bug since the regex is matching it on my end.

  50. DenkZEIT » Blog Archive » Neues Wordpress-plugin installiert: CodeHighlighter says:

    [...] CodeHighlighter bin ich fndig geworden. Alternativ hatte ich mir noch Code Snippet angesehen. Letzteres war mir aber zu Astronautisch mit Zeug, das ich nicht brauche. Z.B. einer [...]

  51. 智熏 says:

    [code lang="php"[

    [/code]
    :)

  52. 智熏 says:

    oops -.-;;

  53. Wyatt says:

    That’s why I added in a preview for this beast :-P

  54. jutirain says:

    Thanks for the great plugin!

    However, does the plugin provide indenting feature?
    Also, I found that the plugin doesn’t work for php…

    The code inside [?php & ?] will be eat up by wordpress. (using brackets deliberately to prevent php being eaten)

    P.S. I’m using wordpress 2.0.2

  55. Wyatt says:

    @jutirain

    > However, does the plugin provide indenting feature?

    Unfortunately, it does not. I have the plan to read from a file on
    the back burner, but it hasn’t been implemented in anything less than
    my local SVN copy.


    > Also, I found that the plugin doesn’t work for php…
    > The code inside [?php & ?] will be eat up by wordpress. (using brackets
    > deliberately to prevent php being eaten)

    <?php

    echo "this is a PHP test.";

    $tmp = array();
    for ($i = 0; $i < 25; $i++) {
        $tmp["myspot" . $i] = $i;
    }
    ?>

    #test some invalid php code
    <?php
    [?php & ?] ; //this should be invalid php code
    //intentionally don’t close the bracket

    Looks like it works here and I haven’t noticed any issues with
    wordpress 2.0.2, but I’d recommend upgrading just for the security
    fixes.

  56. Code Snippet_Wordpress plugin says:

    [...] I’m attempting to keep his wonderful contribution available so I’ve given it a home at http://blog.hackerforhire.org/code-snippet/. If you find any bugs with it, let me know and I will do my best to resovle [...]

  57. TechnoTinkering » Blog Archive » Finally, close but not perfect says:

    [...] http://blog.hackerforhire.org/code-snippet/ [...]

  58. Wp Wordpress » Blog Archive » Code Snippet says:

    [...] I’m attempting to keep his wonderful contribution available so I’ve given it a home at http://blog.hackerforhire.org/code-snippet/. If you find any bugs with it, let me know and I will do my best to resovle [...]

  59. Lee says:

    I also have the same issue jutirain has. WP eats the code.

  60. Wyatt says:

    <?php

    function foo($bar) {
        $i = 0;
        for($i = 0; $i < count($bar); $i++) {
            print($bar[$i]);
        }
    }
    ?>

    [code lang="php"]
    <?php

    function foo($bar) {
        $i = 0;
        for($i = 0; $i < count($bar); $i++) {
            print($bar[$i]);
        }
    }
    ?>
    [/code ] minus the space so it will print out properly

  61. chaozz@work » Blog Archive » My flatfile database system (3) says:

    [...] snippets in this Wordpress post I use a plugin called CodeSnippet, which can be downloaded here: http://blog.hackerforhire.org/code-snippet/ Category: Development  |  Comment (RSS) [...]

  62. Team Programming Dragon.編程龍 » Blog Archive » WordPress Plugin for Code Display says:

    [...] 當中的 display,應該是目前看過 plugin 數最多的一個需求了,諸如 Code Markup, Code Snippet, CodeHighlight, iG: Syntax Hiliter, Preserve Code Formatting [...]

  63. Ciekawe pluginy do Wordpressa | Spam Factory says:

    [...] Code snippet - plugin do wyświetlania kodu (np. php - można zdefiniować w jakim języku kod wklejamy) na naszym blogu. Poniżej przykład z php if(isset($_GET[‘c’])) {$c = $_GET[‘c’]; if($userInfo = checkValidationCode($c)){ /*Check validation code*/ $email = $userInfo[‘user_email’]; } else $error = “The verification code is not valid.”; } else $error = “The verification code is not valid.”; [...]

  64. Pixelsetzer » » Code Snippet Plugin says:

    [...] hinzufügen. Wer das Plugin haben möchte, kann mal die Seite des Herstellers besuchen: klick Da ich selber erst seit kurzen mit Wordpress arbeite, werde wohl noch mehr Artikel zum Thema [...]

  65. harbrigging says:

    Someone submit this to programminghelp.com forum site please! Thanks!!!

  66. Afficher du code dans WordPress via une extension - Blue Cosmos Team Blog says:

    [...] conséquent, j’ai trouvé ici une extension qui gère plus de 50 langages de programmation. Pour l’utiliser il suffit [...]

  67. Perseverance Trumps Talent » Blog Archive » Testing out Code Snippet 2.0 says:

    [...] The folks over at Hacker for Hire have a great plugin for Wordpress called Code Snippet 2.0. [...]

Leave a Reply