WP Plugin: Code Viewer

Code Viewer is a WordPress plugin that pulls source code from an external file and displays it, optionally adding a link to download the code directly. The plugin displays the code with proper indentation, line numbers, and automatic long-line wrapping.

When using Code Viewer, you no longer have to worry about typing countless entity references in order to make your code “HTML friendly” or to simulate tabs…it’s all done automatically with PHP and a little CSS. By inserting line numbers on your page, the plugin also eliminates the problem of long, non-breaking lines screwing up your layout. In addition, line numbers make convenient reference points when discussing code samples.

Last, but not least…because you’re pulling the source code from an external file (rather than having it embedded directly in your entry), the same code can be repeated on numerous pages, and you only have to type it in once. This not only saves you time, but when you update the code in the centralized file, all instances of that code will be updated along with it.

Installation

I am no longer maintaining Code Viewer, please see Current Status of the Code Viewer Wordpress Plugin for more details on where to get the latest version.

  1. Download Code Viewer v1.1
  2. Open the downloaded file in a text editor and configure the $default_path variable (found on line 12), setting it equal to the absolute path of your code folder
  3. Save the edited file
  4. Change the extension of the saved file from .txt to .php
  5. Upload the changed file into your wp-content/plugins/ directory.
  6. Activate the plugin on your WP Admin » Plugin Management page by clicking the corresponding “Activate” link under the Action column.

You’ll also want to add some new classes to your CSS that will control the look of the code listing. Everything (with the exception of auto-indention) works just fine without the CSS; but adding it in makes a huge difference on readability. Feel free to change these values to whatever you like, but this is how I have mine set up:

/* ---( CODE VIEWER FORMATTING )------------------------- */

ol.codelist {
    border: 1px solid #DDD;
    color: #C63;
    font-family: "Courier New", Courier, monospace;
    line-height: 130%;
    padding: 12px 12px 12px 45px;
    margin: 1.5em 0;
    }

ol.codelist li {
    margin: 0;
    padding: 1px 2px;
    }

ol.codelist li.tab0 { padding-left: 2px; }
ol.codelist li.tab1 { padding-left: 26px; }
ol.codelist li.tab2 { padding-left: 50px; }
ol.codelist li.tab3 { padding-left: 74px; }
ol.codelist li.tab4 { padding-left: 98px; }
ol.codelist li.tab5 { padding-left: 122px; }
ol.codelist li.tab6 { padding-left: 146px; }
ol.codelist li.tab7 { padding-left: 170px; }

ol.codelist li.odd { background-color: #FFF; }
ol.codelist li.even { background-color: #F0F0F0; }

ol.codelist li.sourcelink {
    color: #000;
    font: 115% Georgia, "Times New Roman", Times, serif;
    list-style: none;
    margin-left: -32px;
    padding-top: .85em;
    text-align: center;
    }

ol.codelist li code { color: #222; }

Usage

Code Viewer basically searches your entry for a custom XML tag named <viewcode />, that tells the server to look at an external file and parse it line-by-line into an ordered list. It can be placed anywhere a block-level tag is valid, and like any empty element in XHTML, the tag must be properly closed.

To better illustrate its usage, the tag used in this entry (to show the code-viewer.css listing above) was:
<viewcode src="2004/09/code-viewer.css" link="yes" />

Parameters

<viewcode src="URL" link="display" />


  • The src attribute is required.
    • "URL" - string - The URL of the code to display. Note that relative paths are in relation to the $default_path variable set during the installation step.
  • The link attribute is optional.
    • "display" - string - Should the link to the code be displayed ("yes"), or not be displayed ("no"). If the link attribute is left out of the tag completely, the value defaults to "no".

Here are some examples of valid syntax recognized by Code Viewer…note that all of these examples point to the same file (assuming the $default_path variable is set to "http://elasticdog.com/code/"):

<viewcode src="http://elasticdog.com/code/example.txt" link="no" />
<viewcode src="http://elasticdog.com/code/example.txt" />
<viewcode src="/code/example.txt" />
<viewcode src="example.txt" />

Each attribute value must be surrounded with double quotes ("), and not single quotes ('), or the tag will not be recognized.

Version History

  • v1.1 (10 Oct 2004) - Fixed blank line detection; no longer confused by whitespace characters.
  • v1.01 (30 Sep 2004) - Update to code-viewer.css; fixed inconsistent font sizing.
  • v1.0 (26 Sep 2004) - Initial release to the public.

Credits

The idea to use ordered lists in XHTML to present code, originated from Simon Willison’s CSS Numbered Code Listings blog entry. The same idea has been used by other designers, and in particular, a fellow WP plugin author named David House…

Looking at David’s code-snippet system, I fell in love with the idea, but thought his implementation could be improved upon. Code Viewer should be much more efficient in comparison and has the added functionality of optional link inclusion, styling differences for every other line, and better URL & file type support. A big thanks goes out to both David and Simon for their contributions to my latest creation.

44 Comments

  1. Ian Barton
    Posted October 3rd, 2004 at 6:32am | Permalink

    I have only just found your plugin, but will certainly be using it. One of my WordPress “blogs”, is a place where I keep my computer notes. Being able to display code linked to an external file will be very useful!

    Ian.

  2. Posted October 12th, 2004 at 7:25am | Permalink

    Great plugin - thanks for sharing!

  3. Posted October 13th, 2004 at 2:06pm | Permalink

    Yo! that one rocks. I had little troubles with the quicktags editor (it always tried to close the tag) but here’s a fix:
    in the quicktags.js add following function:

    function edInsertCodeview (myField) {
    	var myValue = prompt('Enter the Path of the as file', '');
    	
    	if (myValue) {
    		myValue = '';
    		edInsertContent(myField, myValue);
    	}
    }
    

    than add following Button somewhere at the start:

    edButtons[edButtons.length] =
    new edButton('ed_codeview'
    ,'codeview'
    ,''
    ,''
    ,'v'
    ,-1
    );
    

    than change the edShowButton function to:

    function edShowButton(button, i) {
    	if (button.id == 'ed_img') {
    		document.write('<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="edInsertImage(edCanvas);" value="' + button.display + '" />');
    	}
    	else if (button.id == 'ed_link') {
    		document.write('<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="edInsertLink(edCanvas, ' + i + ');" value="' + button.display + '" />');
    	}
    	else if (button.id == 'ed_codeview'){
    		document.write('<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="edInsertCodeview(edCanvas, ' + i + ');" value="' + button.display + '"  />');
    	} else {
    		document.write('<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="edInsertTag(edCanvas, ' + i + ');" value="' + button.display + '"  />');
    	}
    }
    

    last one: replace line 19 with this one:

    $count = preg_match_all('//', $text, $matches);
    

    g’nite ;-) and good job Aaron!

  4. Posted November 7th, 2004 at 5:41am | Permalink

    Thanks a lot, I’m fitting this into my new design! :)

  5. Posted January 26th, 2005 at 3:43am | Permalink

    This plugin is great, but do you plan to have an inline version where the code is part of the post but it can either create the file or just make one for downloading puposes?

  6. Posted January 28th, 2005 at 5:43am | Permalink

    since i installed the plugin my XHTML wont validate im getting a closing viewtag in the output that shouldnt be there is this the plugin or somthing in wordpress ?

    anyone any ideas ?

  7. Posted February 15th, 2005 at 4:56pm | Permalink

    Is there anyway to make it so that when someone tries to copy and paste code, make it so that they don’t also copy the numbers of the ordered list?

  8. Posted February 17th, 2005 at 11:07pm | Permalink

    Dantheman…you probably have WP set to “correct” invalidly nested XHTML in your Options. It’s trying to close the tag in your post for you. Turn off that option, and you should be validated.

  9. Posted February 19th, 2005 at 6:12pm | Permalink

    Great plugin! Any plans to add to the plugin so that a quicktag is added on the WP write screen? It’d save from having to remember the syntax of the viewcode tag.

  10. Posted February 19th, 2005 at 6:15pm | Permalink

    Also…I attempted to use the parameter like src=”/code/example.txt”, but when the link to the file was created, the link was to the location in my server directory structure, not to the URL. Would be nice to be able to use relative links.

  11. Posted February 19th, 2005 at 11:18pm | Permalink

    Hi,

    I added a little functionality to this beautifull script, so that the code is hidden & has a show/hide link.

    I changed the $codelist = ‘…’; line to this:

    $codelist = '<a href="#" onclick="showhide('."'$path'".');return false">Show/Hide Code</a><ol id="'.$path.'" class="codelist" style="display: none;">' . "\n";
    

    And this is the code to add at the end of the source-viewer.php file:

    function sourceviewerjs()
    {
    ?>
    <script type="text/javascript" language="JavaScript">
    <!--
    var state = 'none';
    
    function showhide(layer_ref) {
    
    if (state == 'block') {
    state = 'none';
    }
    else {
    state = 'block';
    }
    if (document.all) { //IS IE 4 or 5 (or 6 beta)
    eval( "document.all." + layer_ref + ".style.display = state");
    }
    if (document.layers) { //IS NETSCAPE 4 or below
    document.layers[layer_ref].display = state;
    }
    if (document.getElementById &&!document.all) {
    hza = document.getElementById(layer_ref);
    hza.style.display = state;
    }
    }
    //-->
    </script>
    <?php
    }
    
    add_action('wp_head', 'sourceviewerjs');
    

  12. Posted February 19th, 2005 at 11:26pm | Permalink

    Sorry for the first post…forgot to “& lt ;” some tags first…

    I guess you could more improve it by adding a xml attribute check that says hide=”yes|no” initialhide=”yes|no” but i don’t have the time now to do so, and…i don’t know enough regexp either…
    so i’ll leave that up to somebody else :-)

    greetz,
    and thanks for this nice script of yours.

    a feature request of me would be to be able to create files from within the wp-admin-interface to eliminate the use of http://ftp…but hey, we can’t have everything :)

  13. Posted February 21st, 2005 at 9:52pm | Permalink

    Can someone explain to me how to convert all the ol and li tags to p and span tag?

    I tried to do it myself but it didn’t work too well. They only reason I want this is because people like to copy and paste, and using ol’s and li’s it copys the numbers.

  14. Posted February 23rd, 2005 at 7:41pm | Permalink

    I went crazy looking for something like this. This was so easy to use and worked on the 1st shot. Thanks man… good stuff! Used it for the 1st time last night.

    Small problem with validation and Wordpress but it was fixed after the “WordPress should correct invalidly nested XHTML automatically” checkbox was UNchecked. (thanks John Serris)

    peace
    -dj stew

  15. Posted March 18th, 2005 at 4:08pm | Permalink

    great plugin just tested it..goodwork!

  16. Posted May 19th, 2005 at 11:50pm | Permalink

    Very nice plugin. I can see the use for showing large blocks of code, but it would be just a bit overkill to use it for quick bits of code. So for that I can just use the CODE tag that WP provides.

    Is there any way to get the inserted code syntax-highlighted as well? Maybe include a language value in the codeview tag to indicate which language to do highlighting for. Is there any way to do that?

  17. Tim
    Posted June 6th, 2005 at 5:03pm | Permalink

    Hey, nice plugin and I want to use it but when I uploaded the php file to the directory specified, it still would not show up at the admin page. Any ideas?

    Thanks.

  18. Werden
    Posted June 8th, 2005 at 2:37pm | Permalink

    Plugin is super! Thanks, it’s really helped me!

  19. AJ
    Posted July 4th, 2005 at 4:35am | Permalink

    Hi! Great idea and great implementation.
    I have a proposal of adding three more arguments:
    begin_line - value of line number where cut starts from
    end_line - value of line number where cut ends
    lines - complicated argument with format like:
    “0-10,20-30″
    meaning display two quotes from source file, first quote from line number 0 to line number 10 and 2nd quote from line number 20 to line number 30.
    So is same as
    And you also can put “…” between code-quotes.

    Thank you.
    AJ

  20. AJ
    Posted July 4th, 2005 at 4:46am | Permalink

    PS: If you agree then I can implement that part and send you source. Gonna do that anyway :)

  21. AJ
    Posted July 4th, 2005 at 8:02am | Permalink

    And I did it
    http://flash.terra.ee/?p=10

  22. minzel
    Posted September 5th, 2005 at 12:41pm | Permalink

    that are a great plugin. thank you and AJ !!

  23. Jan
    Posted October 15th, 2005 at 4:33am | Permalink

    How can I prevent to display line number by Download link if I use:

    I see in my blog on the line with download link the line number also ;(

  24. Kristian
    Posted October 20th, 2005 at 9:05am | Permalink

    thank you very much for this nice plugin. After some small changes it fits perfectly in my design.

  25. Posted October 30th, 2005 at 1:23pm | Permalink

    nice plugin

  26. Posted January 15th, 2006 at 7:02pm | Permalink

    Thanks a lot. Just works fine and easy to use.

  27. Posted January 24th, 2006 at 6:30pm | Permalink

    Hi,
    I was wondering about the CSS. How do you select the css file and is there any CSS file with the correct highlighting of PHP, Java Script Perl, etc. Also if there was a CSS file that did all that would it need the tags (e.g. #code or something like that) if so would I have to add the tags for each thing I want colored? Thanks

  28. Posted February 25th, 2006 at 7:59pm | Permalink

    Hi,
    I just thought of how to get the code to highlight… Example : First have 2 or a 2 parted style sheet for PHP and html. Then when the code goes threw the plugin for example using something like streplace or something like that to replace and code like “<b>” would become &lt;b&gt;… How’s that sound, I’m not really good at PHP yet but I thought that this would work… Would it ? Thanks.

  29. Posted August 11th, 2006 at 4:16pm | Permalink

    I’ve noticed that the tags are removed by the WYSIWG editor whenever I try to go back and edit a post. Is there a fix for that?

    Also, the link to code-viewer.css above is missing (did you edit this post using the WYSIWG editor?). Is there someplace I can download you css file?

    Thanks.

  30. Posted August 17th, 2006 at 2:20pm | Permalink

    I have modified the CodeViewer Script to work with a WYSIWYG-editor. You can find the script on
    http://www.familjencarlstrom.se/WordPress/?p=141
    Thanx to Aaron Schaefer to a good work :)

  31. Posted August 25th, 2006 at 11:58pm | Permalink

    Nice plugin. Thanks for the hard work, will give it a try on my blog.

  32. Alex
    Posted September 13th, 2006 at 10:54am | Permalink

    How do I make the CSS code for it?

  33. Matt
    Posted October 19th, 2006 at 1:03pm | Permalink

    Hey, I installed the Code Viewer plugin a week or so ago, and I haven’t been able to fix a slight problem. I’ve never written more .php than just to follow along the main tutorial a few years ago.

    Anyway, I messed around w/ code-viewer.php and was able to print up which scenarios were being treaded (which if-else branch was used), but I just can’t get around resolve why the source code is printed up, but the link to the source file resolves to localhost/var/www/…

    Aditionally, the path in the caption displayed for the link is correct, while the actual link is incorrect.

  34. Matt
    Posted October 19th, 2006 at 1:06pm | Permalink

    Anyone find a way for tabs in source code to continue to be represented once code is read in through the plugin to the post?

  35. Matt
    Posted October 19th, 2006 at 2:19pm | Permalink

    The problem that I mentioned above occurs in scenario 2:

    } else if (substr(($matches[1][$i]), 0, 1) == '/') {
    	$path = $_SERVER['DOCUMENT_ROOT'] . $matches[1][$i];
    

    Relative paths in the viewcode src beginning with a slash are resolved to their absolute location on the filesystem and this is appended to the internet location - http://localhost/var/www/htdocs/sources/...

  36. Matt
    Posted October 19th, 2006 at 3:25pm | Permalink

    Spaces resoved:

    The present code only sets the name of the li class to tab and the number of empty space characters found. To indent the code based on spacing, I had to add two things:

    } else {
    	$numtabs = strlen($line) - strlen(ltrim($line));  // determine the number of tabs
    	$line = trim($line);                              // trim leading/trailing whitespace
    

    Create indentation –> $indent = str_repeat(' ', $numtabs);
    Insert indentation –> $codelist .= "\t" . '<code>' .$indent. htmlspecialchars($line) . '</code>' . "\n";

  37. Posted October 26th, 2006 at 10:48am | Permalink

    Sorry, but I had to do that… the unclosed tag was drivin me mad!

  38. Posted October 31st, 2006 at 12:31pm | Permalink

    Am I blind or has the CSS gone missing?

  39. Gilbert Jorgensen
    Posted January 19th, 2007 at 3:52am | Permalink

    The CSS is available at http://flash.terra.ee/?p=10

  40. Dan
    Posted January 28th, 2007 at 9:17pm | Permalink

    Hi,
    I have just tried this in wordpress 2.1 - At first it works fine, displays the code nicely, but whenever I go to edit the post and access the HTML I get:

    rather than what I put in which was:

    If i save any changes then the code is no longer displayed :(
    Wish I could get this right as it looks a sweet plugin!
    Cheers,
    Dan

  41. Dan
    Posted January 28th, 2007 at 9:30pm | Permalink

    Just realised that my code got stripped out :S
    Apologies. Basically it replaces my one tag that has the data in it with an open and close tag that has no data.

    into:

  42. David House
    Posted February 25th, 2007 at 4:16pm | Permalink

    Hi Aaron!

    Great job with this plugin. I’m revamping my website at the moment, and one of the jobs is to upgrade WordPress to the latest version. Seeing as my grabcode plugin is now a bit antiquated, I thought I’d google for a replacement. This is just what I need, and wow, it’s even based on my own older plugin! Hehe. It’s a small web.

    I made a small alteration, creating a $default_uri variable alongside $default_path. This forms the base of the ‘Download this snippet’ links. Your current code uses the same variable as a parameter to file() (which expects a filesystem path) and in the href attribute (which expects a URL). The reason it works is that you can pass a URL to file(), too, but this won’t work on systems with tought security. A two-variable approach, one to hold the filesystem path to the snippets folder, and one to hold the URL to it, is somewhat cleaner and more portable.

    Here’s my diff, in unified diff format: http://pastebin.com/888795

  43. Posted May 22nd, 2007 at 3:59am | Permalink

    Excellent plugin! thanks

  44. Posted July 18th, 2007 at 1:48pm | Permalink

    I have modified the CodeViewer Script (now version 1.4.3) to work with a WYSIWYG-editor and highlighting using GeSHi. You can find the script on
    http://www.familjencarlstrom.se/WordPress/?p=141

Post a Comment

Your email address is never published nor shared. Required fields are marked *

*
*